diff --git a/ajax/libs/rxjs/2.2.28/rx.aggregates.js b/ajax/libs/rxjs/2.2.28/rx.aggregates.js new file mode 100644 index 000000000..032a2a166 --- /dev/null +++ b/ajax/libs/rxjs/2.2.28/rx.aggregates.js @@ -0,0 +1,702 @@ +// 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 (typeof define === 'function' && define.amd) { + define(['rx', 'exports'], function (Rx, exports) { + root.Rx = factory(root, exports, Rx); + return root.Rx; + }); + } 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, + CompositeDisposable = Rx.CompositeDisposable, + AnonymousObservable = Rx.AnonymousObservable, + isEqual = Rx.internals.isEqual, + helpers = Rx.helpers, + defaultComparer = helpers.defaultComparer, + identity = helpers.identity, + defaultSubComparer = helpers.defaultSubComparer, + isPromise = helpers.isPromise, + observableFromPromise = Observable.fromPromise; + + // Defaults + var argumentOutOfRange = 'Argument out of range', + sequenceContainsNoElements = "Sequence contains no elements."; + + observableProto.finalValue = function () { + var source = this; + return new AnonymousObservable(function (observer) { + var hasValue = false, value; + return source.subscribe(function (x) { + hasValue = true; + value = x; + }, observer.onError.bind(observer), function () { + if (!hasValue) { + observer.onError(new Error(sequenceContainsNoElements)); + } else { + observer.onNext(value); + observer.onCompleted(); + } + }); + }); + }; + + function extremaBy(source, keySelector, comparer) { + return new AnonymousObservable(function (observer) { + var hasValue = false, lastKey = null, list = []; + return source.subscribe(function (x) { + var comparison, key; + try { + key = keySelector(x); + } catch (ex) { + observer.onError(ex); + return; + } + comparison = 0; + if (!hasValue) { + hasValue = true; + lastKey = key; + } else { + try { + comparison = comparer(key, lastKey); + } catch (ex1) { + observer.onError(ex1); + return; + } + } + if (comparison > 0) { + lastKey = key; + list = []; + } + if (comparison >= 0) { + list.push(x); + } + }, observer.onError.bind(observer), function () { + observer.onNext(list); + observer.onCompleted(); + }); + }); + } + + function firstOnly(x) { + if (x.length === 0) { + throw new Error(sequenceContainsNoElements); + } + return x[0]; + } + + /** + * Applies an accumulator function over an observable sequence, returning the result of the aggregation as a single element in the result sequence. The specified seed value is used as the initial accumulator value. + * For aggregation behavior with incremental intermediate results, see Observable.scan. + * @example + * 1 - res = source.aggregate(function (acc, x) { return acc + x; }); + * 2 - res = source.aggregate(0, function (acc, x) { return acc + x; }); + * @param {Mixed} [seed] The initial accumulator value. + * @param {Function} accumulator An accumulator function to be invoked on each element. + * @returns {Observable} An observable sequence containing a single element with the final accumulator value. + */ + observableProto.aggregate = function () { + var seed, hasSeed, accumulator; + if (arguments.length === 2) { + seed = arguments[0]; + hasSeed = true; + accumulator = arguments[1]; + } else { + accumulator = arguments[0]; + } + return hasSeed ? this.scan(seed, accumulator).startWith(seed).finalValue() : this.scan(accumulator).finalValue(); + }; + + /** + * Applies an accumulator function over an observable sequence, returning the result of the aggregation as a single element in the result sequence. The specified seed value is used as the initial accumulator value. + * For aggregation behavior with incremental intermediate results, see Observable.scan. + * @example + * 1 - res = source.reduce(function (acc, x) { return acc + x; }); + * 2 - res = source.reduce(function (acc, x) { return acc + x; }, 0); + * @param {Function} accumulator An accumulator function to be invoked on each element. + * @param {Any} [seed] The initial accumulator value. + * @returns {Observable} An observable sequence containing a single element with the final accumulator value. + */ + observableProto.reduce = function (accumulator) { + var seed, hasSeed; + if (arguments.length === 2) { + hasSeed = true; + seed = arguments[1]; + } + return hasSeed ? this.scan(seed, accumulator).startWith(seed).finalValue() : this.scan(accumulator).finalValue(); + }; + + /** + * Determines whether any element of an observable sequence satisfies a condition if present, else if any items are in the sequence. + * @example + * var result = source.any(); + * var result = source.any(function (x) { return x > 3; }); + * @param {Function} [predicate] A function to test each element for a condition. + * @returns {Observable} An observable sequence containing a single element determining whether any elements in the source sequence pass the test in the specified predicate if given, else if any items are in the sequence. + */ + observableProto.some = observableProto.any = function (predicate, thisArg) { + var source = this; + return predicate ? + source.where(predicate, thisArg).any() : + new AnonymousObservable(function (observer) { + return source.subscribe(function () { + observer.onNext(true); + observer.onCompleted(); + }, observer.onError.bind(observer), function () { + observer.onNext(false); + observer.onCompleted(); + }); + }); + }; + + /** + * Determines whether an observable sequence is empty. + * + * @memberOf Observable# + * @returns {Observable} An observable sequence containing a single element determining whether the source sequence is empty. + */ + observableProto.isEmpty = function () { + return this.any().select(function (b) { return !b; }); + }; + + /** + * Determines whether all elements of an observable sequence satisfy a condition. + * + * 1 - res = source.all(function (value) { return value.length > 3; }); + * @memberOf Observable# + * @param {Function} [predicate] A function to test each element for a condition. + * @param {Any} [thisArg] Object to use as this when executing callback. + * @returns {Observable} An observable sequence containing a single element determining whether all elements in the source sequence pass the test in the specified predicate. + */ + observableProto.every = observableProto.all = function (predicate, thisArg) { + return this.where(function (v) { + return !predicate(v); + }, thisArg).any().select(function (b) { + return !b; + }); + }; + + /** + * Determines whether an observable sequence contains a specified element with an optional equality comparer. + * @example + * 1 - res = source.contains(42); + * 2 - res = source.contains({ value: 42 }, function (x, y) { return x.value === y.value; }); + * @param value The value to locate in the source sequence. + * @param {Function} [comparer] An equality comparer to compare elements. + * @returns {Observable} An observable sequence containing a single element determining whether the source sequence contains an element that has the specified value. + */ + observableProto.contains = function (value, comparer) { + comparer || (comparer = defaultComparer); + return this.where(function (v) { + return comparer(v, value); + }).any(); + }; + + /** + * Returns an observable sequence containing a value that represents how many elements in the specified observable sequence satisfy a condition if provided, else the count of items. + * @example + * res = source.count(); + * res = source.count(function (x) { return x > 3; }); + * @param {Function} [predicate]A function to test each element for a condition. + * @param {Any} [thisArg] Object to use as this when executing callback. + * @returns {Observable} An observable sequence containing a single element with a number that represents how many elements in the input sequence satisfy the condition in the predicate function if provided, else the count of items in the sequence. + */ + observableProto.count = function (predicate, thisArg) { + return predicate ? + this.where(predicate, thisArg).count() : + this.aggregate(0, function (count) { + return count + 1; + }); + }; + + /** + * Computes the sum of a sequence of values that are obtained by invoking an optional transform function on each element of the input sequence, else if not specified computes the sum on each item in the sequence. + * @example + * var res = source.sum(); + * var res = source.sum(function (x) { return x.value; }); + * @param {Function} [selector] A transform function to apply to each element. + * @param {Any} [thisArg] Object to use as this when executing callback. + * @returns {Observable} An observable sequence containing a single element with the sum of the values in the source sequence. + */ + observableProto.sum = function (keySelector, thisArg) { + return keySelector ? + this.select(keySelector, thisArg).sum() : + this.aggregate(0, function (prev, curr) { + return prev + curr; + }); + }; + + /** + * Returns the elements in an observable sequence with the minimum key value according to the specified comparer. + * @example + * var res = source.minBy(function (x) { return x.value; }); + * var res = source.minBy(function (x) { return x.value; }, function (x, y) { return x - y; }); + * @param {Function} keySelector Key selector function. + * @param {Function} [comparer] Comparer used to compare key values. + * @returns {Observable} An observable sequence containing a list of zero or more elements that have a minimum key value. + */ + observableProto.minBy = function (keySelector, comparer) { + comparer || (comparer = defaultSubComparer); + return extremaBy(this, keySelector, function (x, y) { + return comparer(x, y) * -1; + }); + }; + + /** + * Returns the minimum element in an observable sequence according to the optional comparer else a default greater than less than check. + * @example + * var res = source.min(); + * var res = source.min(function (x, y) { return x.value - y.value; }); + * @param {Function} [comparer] Comparer used to compare elements. + * @returns {Observable} An observable sequence containing a single element with the minimum element in the source sequence. + */ + observableProto.min = function (comparer) { + return this.minBy(identity, comparer).select(function (x) { + return firstOnly(x); + }); + }; + + /** + * Returns the elements in an observable sequence with the maximum key value according to the specified comparer. + * @example + * var res = source.maxBy(function (x) { return x.value; }); + * var res = source.maxBy(function (x) { return x.value; }, function (x, y) { return x - y;; }); + * @param {Function} keySelector Key selector function. + * @param {Function} [comparer] Comparer used to compare key values. + * @returns {Observable} An observable sequence containing a list of zero or more elements that have a maximum key value. + */ + observableProto.maxBy = function (keySelector, comparer) { + comparer || (comparer = defaultSubComparer); + return extremaBy(this, keySelector, comparer); + }; + + /** + * Returns the maximum value in an observable sequence according to the specified comparer. + * @example + * var res = source.max(); + * var res = source.max(function (x, y) { return x.value - y.value; }); + * @param {Function} [comparer] Comparer used to compare elements. + * @returns {Observable} An observable sequence containing a single element with the maximum element in the source sequence. + */ + observableProto.max = function (comparer) { + return this.maxBy(identity, comparer).select(function (x) { + return firstOnly(x); + }); + }; + + /** + * Computes the average of an observable sequence of values that are in the sequence or obtained by invoking a transform function on each element of the input sequence if present. + * @example + * var res = res = source.average(); + * var res = res = source.average(function (x) { return x.value; }); + * @param {Function} [selector] A transform function to apply to each element. + * @param {Any} [thisArg] Object to use as this when executing callback. + * @returns {Observable} An observable sequence containing a single element with the average of the sequence of values. + */ + observableProto.average = function (keySelector, thisArg) { + return keySelector ? + this.select(keySelector, thisArg).average() : + this.scan({ + sum: 0, + count: 0 + }, function (prev, cur) { + return { + sum: prev.sum + cur, + count: prev.count + 1 + }; + }).finalValue().select(function (s) { + if (s.count === 0) { + throw new Error('The input sequence was empty'); + } + return s.sum / s.count; + }); + }; + + function sequenceEqualArray(first, second, comparer) { + return new AnonymousObservable(function (observer) { + var count = 0, len = second.length; + return first.subscribe(function (value) { + var equal = false; + try { + if (count < len) { + equal = comparer(value, second[count++]); + } + } catch (e) { + observer.onError(e); + return; + } + if (!equal) { + observer.onNext(false); + observer.onCompleted(); + } + }, observer.onError.bind(observer), function () { + observer.onNext(count === len); + observer.onCompleted(); + }); + }); + } + + /** + * Determines whether two sequences are equal by comparing the elements pairwise using a specified equality comparer. + * + * @example + * var res = res = source.sequenceEqual([1,2,3]); + * var res = res = source.sequenceEqual([{ value: 42 }], function (x, y) { return x.value === y.value; }); + * 3 - res = source.sequenceEqual(Rx.Observable.returnValue(42)); + * 4 - res = source.sequenceEqual(Rx.Observable.returnValue({ value: 42 }), function (x, y) { return x.value === y.value; }); + * @param {Observable} second Second observable sequence or array to compare. + * @param {Function} [comparer] Comparer used to compare elements of both sequences. + * @returns {Observable} An observable sequence that contains a single element which indicates whether both sequences are of equal length and their corresponding elements are equal according to the specified equality comparer. + */ + observableProto.sequenceEqual = function (second, comparer) { + var first = this; + comparer || (comparer = defaultComparer); + if (Array.isArray(second)) { + return sequenceEqualArray(first, second, comparer); + } + return new AnonymousObservable(function (observer) { + var donel = false, doner = false, ql = [], qr = []; + var subscription1 = first.subscribe(function (x) { + var equal, v; + if (qr.length > 0) { + v = qr.shift(); + try { + equal = comparer(v, x); + } catch (e) { + observer.onError(e); + return; + } + if (!equal) { + observer.onNext(false); + observer.onCompleted(); + } + } else if (doner) { + observer.onNext(false); + observer.onCompleted(); + } else { + ql.push(x); + } + }, observer.onError.bind(observer), function () { + donel = true; + if (ql.length === 0) { + if (qr.length > 0) { + observer.onNext(false); + observer.onCompleted(); + } else if (doner) { + observer.onNext(true); + observer.onCompleted(); + } + } + }); + + isPromise(second) && (second = observableFromPromise(second)); + var subscription2 = second.subscribe(function (x) { + var equal, v; + if (ql.length > 0) { + v = ql.shift(); + try { + equal = comparer(v, x); + } catch (exception) { + observer.onError(exception); + return; + } + if (!equal) { + observer.onNext(false); + observer.onCompleted(); + } + } else if (donel) { + observer.onNext(false); + observer.onCompleted(); + } else { + qr.push(x); + } + }, observer.onError.bind(observer), function () { + doner = true; + if (qr.length === 0) { + if (ql.length > 0) { + observer.onNext(false); + observer.onCompleted(); + } else if (donel) { + observer.onNext(true); + observer.onCompleted(); + } + } + }); + return new CompositeDisposable(subscription1, subscription2); + }); + }; + + function elementAtOrDefault(source, index, hasDefault, defaultValue) { + if (index < 0) { + throw new Error(argumentOutOfRange); + } + return new AnonymousObservable(function (observer) { + var i = index; + return source.subscribe(function (x) { + if (i === 0) { + observer.onNext(x); + observer.onCompleted(); + } + i--; + }, observer.onError.bind(observer), function () { + if (!hasDefault) { + observer.onError(new Error(argumentOutOfRange)); + } else { + observer.onNext(defaultValue); + observer.onCompleted(); + } + }); + }); + } + + /** + * Returns the element at a specified index in a sequence. + * @example + * var res = source.elementAt(5); + * @param {Number} index The zero-based index of the element to retrieve. + * @returns {Observable} An observable sequence that produces the element at the specified position in the source sequence. + */ + observableProto.elementAt = function (index) { + return elementAtOrDefault(this, index, false); + }; + + /** + * Returns the element at a specified index in a sequence or a default value if the index is out of range. + * @example + * var res = source.elementAtOrDefault(5); + * var res = source.elementAtOrDefault(5, 0); + * @param {Number} index The zero-based index of the element to retrieve. + * @param [defaultValue] The default value if the index is outside the bounds of the source sequence. + * @returns {Observable} An observable sequence that produces the element at the specified position in the source sequence, or a default value if the index is outside the bounds of the source sequence. + */ + observableProto.elementAtOrDefault = function (index, defaultValue) { + return elementAtOrDefault(this, index, true, defaultValue); + }; + + function singleOrDefaultAsync(source, hasDefault, defaultValue) { + return new AnonymousObservable(function (observer) { + var value = defaultValue, seenValue = false; + return source.subscribe(function (x) { + if (seenValue) { + observer.onError(new Error('Sequence contains more than one element')); + } else { + value = x; + seenValue = true; + } + }, observer.onError.bind(observer), function () { + if (!seenValue && !hasDefault) { + observer.onError(new Error(sequenceContainsNoElements)); + } else { + observer.onNext(value); + observer.onCompleted(); + } + }); + }); + } + + /** + * Returns the only element of an observable sequence that satisfies the condition in the optional predicate, and reports an exception if there is not exactly one element in the observable sequence. + * @example + * var res = res = source.single(); + * var res = res = source.single(function (x) { return x === 42; }); + * @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence. + * @param {Any} [thisArg] Object to use as `this` when executing the predicate. + * @returns {Observable} Sequence containing the single element in the observable sequence that satisfies the condition in the predicate. + */ + observableProto.single = function (predicate, thisArg) { + return predicate ? + this.where(predicate, thisArg).single() : + singleOrDefaultAsync(this, false); + }; + + /** + * Returns the only element of an observable sequence that matches the predicate, or a default value if no such element exists; this method reports an exception if there is more than one element in the observable sequence. + * @example + * var res = res = source.singleOrDefault(); + * var res = res = source.singleOrDefault(function (x) { return x === 42; }); + * res = source.singleOrDefault(function (x) { return x === 42; }, 0); + * res = source.singleOrDefault(null, 0); + * @memberOf Observable# + * @param {Function} predicate A predicate function to evaluate for elements in the source sequence. + * @param [defaultValue] The default value if the index is outside the bounds of the source sequence. + * @param {Any} [thisArg] Object to use as `this` when executing the predicate. + * @returns {Observable} Sequence containing the single element in the observable sequence that satisfies the condition in the predicate, or a default value if no such element exists. + */ + observableProto.singleOrDefault = function (predicate, defaultValue, thisArg) { + return predicate? + this.where(predicate, thisArg).singleOrDefault(null, defaultValue) : + singleOrDefaultAsync(this, true, defaultValue) + }; + function firstOrDefaultAsync(source, hasDefault, defaultValue) { + return new AnonymousObservable(function (observer) { + return source.subscribe(function (x) { + observer.onNext(x); + observer.onCompleted(); + }, observer.onError.bind(observer), function () { + if (!hasDefault) { + observer.onError(new Error(sequenceContainsNoElements)); + } else { + observer.onNext(defaultValue); + observer.onCompleted(); + } + }); + }); + } + + /** + * Returns the first element of an observable sequence that satisfies the condition in the predicate if present else the first item in the sequence. + * @example + * var res = res = source.first(); + * var res = res = source.first(function (x) { return x > 3; }); + * @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence. + * @param {Any} [thisArg] Object to use as `this` when executing the predicate. + * @returns {Observable} Sequence containing the first element in the observable sequence that satisfies the condition in the predicate if provided, else the first item in the sequence. + */ + observableProto.first = function (predicate, thisArg) { + return predicate ? + this.where(predicate, thisArg).first() : + firstOrDefaultAsync(this, false); + }; + + /** + * Returns the first element of an observable sequence that satisfies the condition in the predicate, or a default value if no such element exists. + * @example + * var res = res = source.firstOrDefault(); + * var res = res = source.firstOrDefault(function (x) { return x > 3; }); + * var res = source.firstOrDefault(function (x) { return x > 3; }, 0); + * var res = source.firstOrDefault(null, 0); + * @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence. + * @param {Any} [defaultValue] The default value if no such element exists. If not specified, defaults to null. + * @param {Any} [thisArg] Object to use as `this` when executing the predicate. + * @returns {Observable} Sequence containing the first element in the observable sequence that satisfies the condition in the predicate, or a default value if no such element exists. + */ + observableProto.firstOrDefault = function (predicate, defaultValue, thisArg) { + return predicate ? + this.where(predicate).firstOrDefault(null, defaultValue) : + firstOrDefaultAsync(this, true, defaultValue); + }; + + function lastOrDefaultAsync(source, hasDefault, defaultValue) { + return new AnonymousObservable(function (observer) { + var value = defaultValue, seenValue = false; + return source.subscribe(function (x) { + value = x; + seenValue = true; + }, observer.onError.bind(observer), function () { + if (!seenValue && !hasDefault) { + observer.onError(new Error(sequenceContainsNoElements)); + } else { + observer.onNext(value); + observer.onCompleted(); + } + }); + }); + } + + /** + * Returns the last element of an observable sequence that satisfies the condition in the predicate if specified, else the last element. + * @example + * var res = source.last(); + * var res = source.last(function (x) { return x > 3; }); + * @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence. + * @param {Any} [thisArg] Object to use as `this` when executing the predicate. + * @returns {Observable} Sequence containing the last element in the observable sequence that satisfies the condition in the predicate. + */ + observableProto.last = function (predicate, thisArg) { + return predicate ? + this.where(predicate, thisArg).last() : + lastOrDefaultAsync(this, false); + }; + + /** + * Returns the last element of an observable sequence that satisfies the condition in the predicate, or a default value if no such element exists. + * @example + * var res = source.lastOrDefault(); + * var res = source.lastOrDefault(function (x) { return x > 3; }); + * var res = source.lastOrDefault(function (x) { return x > 3; }, 0); + * var res = source.lastOrDefault(null, 0); + * @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence. + * @param [defaultValue] The default value if no such element exists. If not specified, defaults to null. + * @param {Any} [thisArg] Object to use as `this` when executing the predicate. + * @returns {Observable} Sequence containing the last element in the observable sequence that satisfies the condition in the predicate, or a default value if no such element exists. + */ + observableProto.lastOrDefault = function (predicate, defaultValue, thisArg) { + return predicate ? + this.where(predicate, thisArg).lastOrDefault(null, defaultValue) : + lastOrDefaultAsync(this, true, defaultValue); + }; + + function findValue (source, predicate, thisArg, yieldIndex) { + return new AnonymousObservable(function (observer) { + var i = 0; + return source.subscribe(function (x) { + var shouldRun; + try { + shouldRun = predicate.call(thisArg, x, i, source); + } catch(e) { + observer.onError(e); + return; + } + if (shouldRun) { + observer.onNext(yieldIndex ? i : x); + observer.onCompleted(); + } else { + i++; + } + }, observer.onError.bind(observer), function () { + observer.onNext(yieldIndex ? -1 : undefined); + observer.onCompleted(); + }); + }); + } + + /** + * Searches for an element that matches the conditions defined by the specified predicate, and returns the first occurrence within the entire Observable sequence. + * @param {Function} predicate The predicate that defines the conditions of the element to search for. + * @param {Any} [thisArg] Object to use as `this` when executing the predicate. + * @returns {Observable} An Observable sequence with the first element that matches the conditions defined by the specified predicate, if found; otherwise, undefined. + */ + observableProto.find = function (predicate, thisArg) { + return findValue(this, predicate, thisArg, false); + }; + + /** + * Searches for an element that matches the conditions defined by the specified predicate, and returns + * an Observable sequence with the zero-based index of the first occurrence within the entire Observable sequence. + * @param {Function} predicate The predicate that defines the conditions of the element to search for. + * @param {Any} [thisArg] Object to use as `this` when executing the predicate. + * @returns {Observable} An Observable sequence with the zero-based index of the first occurrence of an element that matches the conditions defined by match, if found; otherwise, –1. + */ + observableProto.findIndex = function (predicate, thisArg) { + return findValue(this, predicate, thisArg, true); + }; + + return Rx; +})); \ No newline at end of file diff --git a/ajax/libs/rxjs/2.2.28/rx.aggregates.min.js b/ajax/libs/rxjs/2.2.28/rx.aggregates.min.js new file mode 100644 index 000000000..4f631a12b --- /dev/null +++ b/ajax/libs/rxjs/2.2.28/rx.aggregates.min.js @@ -0,0 +1 @@ +(function(t){var e={"boolean":!1,"function":!0,object:!0,number:!1,string:!1,undefined:!1},n=e[typeof window]&&window||this,r=e[typeof exports]&&exports&&!exports.nodeType&&exports,i=e[typeof module]&&module&&!module.nodeType&&module,o=(i&&i.exports===r&&r,e[typeof global]&&global);!o||o.global!==o&&o.window!==o||(n=o),"function"==typeof define&&define.amd?define(["rx","exports"],function(e,r){return n.Rx=t(n,r,e),n.Rx}):"object"==typeof module&&module&&module.exports===r?module.exports=t(n,module.exports,require("./rx")):n.Rx=t(n,{},n.Rx)}).call(this,function(t,e,n,r){function i(t,e,n){return new v(function(i){var o=!1,s=null,u=[];return t.subscribe(function(t){var c,a;try{a=e(t)}catch(h){return i.onError(h),r}if(c=0,o)try{c=n(a,s)}catch(l){return i.onError(l),r}else o=!0,s=a;c>0&&(s=a,u=[]),c>=0&&u.push(t)},i.onError.bind(i),function(){i.onNext(u),i.onCompleted()})})}function o(t){if(0===t.length)throw Error(C);return t[0]}function s(t,e,n){return new v(function(i){var o=0,s=e.length;return t.subscribe(function(t){var u=!1;try{s>o&&(u=n(t,e[o++]))}catch(c){return i.onError(c),r}u||(i.onNext(!1),i.onCompleted())},i.onError.bind(i),function(){i.onNext(o===s),i.onCompleted()})})}function u(t,e,n,r){if(0>e)throw Error(x);return new v(function(i){var o=e;return t.subscribe(function(t){0===o&&(i.onNext(t),i.onCompleted()),o--},i.onError.bind(i),function(){n?(i.onNext(r),i.onCompleted()):i.onError(Error(x))})})}function c(t,e,n){return new v(function(r){var i=n,o=!1;return t.subscribe(function(t){o?r.onError(Error("Sequence contains more than one element")):(i=t,o=!0)},r.onError.bind(r),function(){o||e?(r.onNext(i),r.onCompleted()):r.onError(Error(C))})})}function a(t,e,n){return new v(function(r){return t.subscribe(function(t){r.onNext(t),r.onCompleted()},r.onError.bind(r),function(){e?(r.onNext(n),r.onCompleted()):r.onError(Error(C))})})}function h(t,e,n){return new v(function(r){var i=n,o=!1;return t.subscribe(function(t){i=t,o=!0},r.onError.bind(r),function(){o||e?(r.onNext(i),r.onCompleted()):r.onError(Error(C))})})}function l(t,e,n,i){return new v(function(o){var s=0;return t.subscribe(function(u){var c;try{c=e.call(n,u,s,t)}catch(a){return o.onError(a),r}c?(o.onNext(i?s:u),o.onCompleted()):s++},o.onError.bind(o),function(){o.onNext(i?-1:r),o.onCompleted()})})}var f=n.Observable,p=f.prototype,d=n.CompositeDisposable,v=n.AnonymousObservable,b=(n.internals.isEqual,n.helpers),m=b.defaultComparer,y=b.identity,w=b.defaultSubComparer,g=b.isPromise,E=f.fromPromise,x="Argument out of range",C="Sequence contains no elements.";return p.finalValue=function(){var t=this;return new v(function(e){var n,r=!1;return t.subscribe(function(t){r=!0,n=t},e.onError.bind(e),function(){r?(e.onNext(n),e.onCompleted()):e.onError(Error(C))})})},p.aggregate=function(){var t,e,n;return 2===arguments.length?(t=arguments[0],e=!0,n=arguments[1]):n=arguments[0],e?this.scan(t,n).startWith(t).finalValue():this.scan(n).finalValue()},p.reduce=function(t){var e,n;return 2===arguments.length&&(n=!0,e=arguments[1]),n?this.scan(e,t).startWith(e).finalValue():this.scan(t).finalValue()},p.some=p.any=function(t,e){var n=this;return t?n.where(t,e).any():new v(function(t){return n.subscribe(function(){t.onNext(!0),t.onCompleted()},t.onError.bind(t),function(){t.onNext(!1),t.onCompleted()})})},p.isEmpty=function(){return this.any().select(function(t){return!t})},p.every=p.all=function(t,e){return this.where(function(e){return!t(e)},e).any().select(function(t){return!t})},p.contains=function(t,e){return e||(e=m),this.where(function(n){return e(n,t)}).any()},p.count=function(t,e){return t?this.where(t,e).count():this.aggregate(0,function(t){return t+1})},p.sum=function(t,e){return t?this.select(t,e).sum():this.aggregate(0,function(t,e){return t+e})},p.minBy=function(t,e){return e||(e=w),i(this,t,function(t,n){return-1*e(t,n)})},p.min=function(t){return this.minBy(y,t).select(function(t){return o(t)})},p.maxBy=function(t,e){return e||(e=w),i(this,t,e)},p.max=function(t){return this.maxBy(y,t).select(function(t){return o(t)})},p.average=function(t,e){return t?this.select(t,e).average():this.scan({sum:0,count:0},function(t,e){return{sum:t.sum+e,count:t.count+1}}).finalValue().select(function(t){if(0===t.count)throw Error("The input sequence was empty");return t.sum/t.count})},p.sequenceEqual=function(t,e){var n=this;return e||(e=m),Array.isArray(t)?s(n,t,e):new v(function(i){var o=!1,s=!1,u=[],c=[],a=n.subscribe(function(t){var n,o;if(c.length>0){o=c.shift();try{n=e(o,t)}catch(a){return i.onError(a),r}n||(i.onNext(!1),i.onCompleted())}else s?(i.onNext(!1),i.onCompleted()):u.push(t)},i.onError.bind(i),function(){o=!0,0===u.length&&(c.length>0?(i.onNext(!1),i.onCompleted()):s&&(i.onNext(!0),i.onCompleted()))});g(t)&&(t=E(t));var h=t.subscribe(function(t){var n,s;if(u.length>0){s=u.shift();try{n=e(s,t)}catch(a){return i.onError(a),r}n||(i.onNext(!1),i.onCompleted())}else o?(i.onNext(!1),i.onCompleted()):c.push(t)},i.onError.bind(i),function(){s=!0,0===c.length&&(u.length>0?(i.onNext(!1),i.onCompleted()):o&&(i.onNext(!0),i.onCompleted()))});return new d(a,h)})},p.elementAt=function(t){return u(this,t,!1)},p.elementAtOrDefault=function(t,e){return u(this,t,!0,e)},p.single=function(t,e){return t?this.where(t,e).single():c(this,!1)},p.singleOrDefault=function(t,e,n){return t?this.where(t,n).singleOrDefault(null,e):c(this,!0,e)},p.first=function(t,e){return t?this.where(t,e).first():a(this,!1)},p.firstOrDefault=function(t,e){return t?this.where(t).firstOrDefault(null,e):a(this,!0,e)},p.last=function(t,e){return t?this.where(t,e).last():h(this,!1)},p.lastOrDefault=function(t,e,n){return t?this.where(t,n).lastOrDefault(null,e):h(this,!0,e)},p.find=function(t,e){return l(this,t,e,!1)},p.findIndex=function(t,e){return l(this,t,e,!0)},n}); \ No newline at end of file diff --git a/ajax/libs/rxjs/2.2.28/rx.all.compat.js b/ajax/libs/rxjs/2.2.28/rx.all.compat.js new file mode 100644 index 000000000..30712de72 --- /dev/null +++ b/ajax/libs/rxjs/2.2.28/rx.all.compat.js @@ -0,0 +1,9421 @@ +// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. + +;(function (undefined) { + + var objectTypes = { + 'boolean': false, + 'function': true, + 'object': true, + 'number': false, + 'string': false, + 'undefined': false + }; + + var root = (objectTypes[typeof window] && window) || this, + freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports, + freeModule = objectTypes[typeof module] && module && !module.nodeType && module, + moduleExports = freeModule && freeModule.exports === freeExports && freeExports, + freeGlobal = objectTypes[typeof global] && global; + + if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal)) { + root = freeGlobal; + } + + var Rx = { + internals: {}, + config: { + Promise: root.Promise // Detect if promise exists + }, + helpers: { } + }; + + // Defaults + var noop = Rx.helpers.noop = function () { }, + identity = Rx.helpers.identity = function (x) { return x; }, + pluck = Rx.helpers.pluck = function (property) { return function (x) { return x[property]; }; }, + just = Rx.helpers.just = function (value) { return function () { return value; }; }, + defaultNow = Rx.helpers.defaultNow = (function () { return !!Date.now ? Date.now : function () { return +new Date; }; }()), + defaultComparer = Rx.helpers.defaultComparer = function (x, y) { return isEqual(x, y); }, + defaultSubComparer = Rx.helpers.defaultSubComparer = function (x, y) { return x > y ? 1 : (x < y ? -1 : 0); }, + defaultKeySerializer = Rx.helpers.defaultKeySerializer = function (x) { return x.toString(); }, + defaultError = Rx.helpers.defaultError = function (err) { throw err; }, + isPromise = Rx.helpers.isPromise = function (p) { return !!p && typeof p.then === 'function' && p.then !== Rx.Observable.prototype.then; }, + asArray = Rx.helpers.asArray = function () { return Array.prototype.slice.call(arguments); }, + not = Rx.helpers.not = function (a) { return !a; }; + + // Errors + var sequenceContainsNoElements = 'Sequence contains no elements.'; + var argumentOutOfRange = 'Argument out of range'; + var objectDisposed = 'Object has been disposed'; + function checkDisposed() { if (this.isDisposed) { throw new Error(objectDisposed); } } + + // Shim in iterator support + var $iterator$ = (typeof Symbol === 'object' && Symbol.iterator) || + '_es6shim_iterator_'; + // Firefox ships a partial implementation using the name @@iterator. + // https://bugzilla.mozilla.org/show_bug.cgi?id=907077#c14 + // So use that name if we detect it. + if (root.Set && typeof new root.Set()['@@iterator'] === 'function') { + $iterator$ = '@@iterator'; + } + var doneEnumerator = { done: true, value: undefined }; + + /** `Object#toString` result shortcuts */ + var argsClass = '[object Arguments]', + arrayClass = '[object Array]', + boolClass = '[object Boolean]', + dateClass = '[object Date]', + errorClass = '[object Error]', + funcClass = '[object Function]', + numberClass = '[object Number]', + objectClass = '[object Object]', + regexpClass = '[object RegExp]', + stringClass = '[object String]'; + + var toString = Object.prototype.toString, + hasOwnProperty = Object.prototype.hasOwnProperty, + supportsArgsClass = toString.call(arguments) == argsClass, // For less -1); + } + }); + } + } + stackA.pop(); + stackB.pop(); + + return result; + } + var slice = Array.prototype.slice; + function argsOrArray(args, idx) { + return args.length === 1 && Array.isArray(args[idx]) ? + args[idx] : + slice.call(args); + } + var hasProp = {}.hasOwnProperty; + + /** @private */ + var inherits = this.inherits = Rx.internals.inherits = function (child, parent) { + function __() { this.constructor = child; } + __.prototype = parent.prototype; + child.prototype = new __(); + }; + + /** @private */ + var addProperties = Rx.internals.addProperties = function (obj) { + var sources = slice.call(arguments, 1); + for (var i = 0, len = sources.length; i < len; i++) { + var source = sources[i]; + for (var prop in source) { + obj[prop] = source[prop]; + } + } + }; + + // Rx Utils + var addRef = Rx.internals.addRef = function (xs, r) { + return new AnonymousObservable(function (observer) { + return new CompositeDisposable(r.getDisposable(), xs.subscribe(observer)); + }); + }; + + // Collection polyfills + function arrayInitialize(count, factory) { + var a = new Array(count); + for (var i = 0; i < count; i++) { + a[i] = factory(); + } + return a; + } + + // Utilities + if (!Function.prototype.bind) { + Function.prototype.bind = function (that) { + var target = this, + args = slice.call(arguments, 1); + var bound = function () { + if (this instanceof bound) { + function F() { } + F.prototype = target.prototype; + var self = new F(); + var result = target.apply(self, args.concat(slice.call(arguments))); + if (Object(result) === result) { + return result; + } + return self; + } else { + return target.apply(that, args.concat(slice.call(arguments))); + } + }; + + return bound; + }; + } + + var boxedString = Object("a"), + splitString = boxedString[0] != "a" || !(0 in boxedString); + if (!Array.prototype.every) { + Array.prototype.every = function every(fun /*, thisp */) { + var object = Object(this), + self = splitString && {}.toString.call(this) == stringClass ? + this.split("") : + object, + length = self.length >>> 0, + thisp = arguments[1]; + + if ({}.toString.call(fun) != funcClass) { + throw new TypeError(fun + " is not a function"); + } + + for (var i = 0; i < length; i++) { + if (i in self && !fun.call(thisp, self[i], i, object)) { + return false; + } + } + return true; + }; + } + + if (!Array.prototype.map) { + Array.prototype.map = function map(fun /*, thisp*/) { + var object = Object(this), + self = splitString && {}.toString.call(this) == stringClass ? + this.split("") : + object, + length = self.length >>> 0, + result = Array(length), + thisp = arguments[1]; + + if ({}.toString.call(fun) != funcClass) { + throw new TypeError(fun + " is not a function"); + } + + for (var i = 0; i < length; i++) { + if (i in self) + result[i] = fun.call(thisp, self[i], i, object); + } + return result; + }; + } + + if (!Array.prototype.filter) { + Array.prototype.filter = function (predicate) { + var results = [], item, t = new Object(this); + for (var i = 0, len = t.length >>> 0; i < len; i++) { + item = t[i]; + if (i in t && predicate.call(arguments[1], item, i, t)) { + results.push(item); + } + } + return results; + }; + } + + if (!Array.isArray) { + Array.isArray = function (arg) { + return Object.prototype.toString.call(arg) == arrayClass; + }; + } + + if (!Array.prototype.indexOf) { + Array.prototype.indexOf = function indexOf(searchElement) { + var t = Object(this); + var len = t.length >>> 0; + if (len === 0) { + return -1; + } + var n = 0; + if (arguments.length > 1) { + n = Number(arguments[1]); + if (n !== n) { + n = 0; + } else if (n !== 0 && n != Infinity && n !== -Infinity) { + n = (n > 0 || -1) * Math.floor(Math.abs(n)); + } + } + if (n >= len) { + return -1; + } + var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0); + for (; k < len; k++) { + if (k in t && t[k] === searchElement) { + return k; + } + } + return -1; + }; + } + + // Collections + var IndexedItem = function (id, value) { + this.id = id; + this.value = value; + }; + + IndexedItem.prototype.compareTo = function (other) { + var c = this.value.compareTo(other.value); + if (c === 0) { + c = this.id - other.id; + } + return c; + }; + + // Priority Queue for Scheduling + var PriorityQueue = Rx.internals.PriorityQueue = function (capacity) { + this.items = new Array(capacity); + this.length = 0; + }; + + var priorityProto = PriorityQueue.prototype; + priorityProto.isHigherPriority = function (left, right) { + return this.items[left].compareTo(this.items[right]) < 0; + }; + + priorityProto.percolate = function (index) { + if (index >= this.length || index < 0) { + return; + } + var parent = index - 1 >> 1; + if (parent < 0 || parent === index) { + return; + } + if (this.isHigherPriority(index, parent)) { + var temp = this.items[index]; + this.items[index] = this.items[parent]; + this.items[parent] = temp; + this.percolate(parent); + } + }; + + priorityProto.heapify = function (index) { + if (index === undefined) { + index = 0; + } + if (index >= this.length || index < 0) { + return; + } + var left = 2 * index + 1, + right = 2 * index + 2, + first = index; + if (left < this.length && this.isHigherPriority(left, first)) { + first = left; + } + if (right < this.length && this.isHigherPriority(right, first)) { + first = right; + } + if (first !== index) { + var temp = this.items[index]; + this.items[index] = this.items[first]; + this.items[first] = temp; + this.heapify(first); + } + }; + + priorityProto.peek = function () { return this.items[0].value; }; + + priorityProto.removeAt = function (index) { + this.items[index] = this.items[--this.length]; + delete this.items[this.length]; + this.heapify(); + }; + + priorityProto.dequeue = function () { + var result = this.peek(); + this.removeAt(0); + return result; + }; + + priorityProto.enqueue = function (item) { + var index = this.length++; + this.items[index] = new IndexedItem(PriorityQueue.count++, item); + this.percolate(index); + }; + + priorityProto.remove = function (item) { + for (var i = 0; i < this.length; i++) { + if (this.items[i].value === item) { + this.removeAt(i); + return true; + } + } + return false; + }; + PriorityQueue.count = 0; + /** + * Represents a group of disposable resources that are disposed together. + * @constructor + */ + var CompositeDisposable = Rx.CompositeDisposable = function () { + this.disposables = argsOrArray(arguments, 0); + this.isDisposed = false; + this.length = this.disposables.length; + }; + + var CompositeDisposablePrototype = CompositeDisposable.prototype; + + /** + * Adds a disposable to the CompositeDisposable or disposes the disposable if the CompositeDisposable is disposed. + * @param {Mixed} item Disposable to add. + */ + CompositeDisposablePrototype.add = function (item) { + if (this.isDisposed) { + item.dispose(); + } else { + this.disposables.push(item); + this.length++; + } + }; + + /** + * Removes and disposes the first occurrence of a disposable from the CompositeDisposable. + * @param {Mixed} item Disposable to remove. + * @returns {Boolean} true if found; false otherwise. + */ + CompositeDisposablePrototype.remove = function (item) { + var shouldDispose = false; + if (!this.isDisposed) { + var idx = this.disposables.indexOf(item); + if (idx !== -1) { + shouldDispose = true; + this.disposables.splice(idx, 1); + this.length--; + item.dispose(); + } + + } + return shouldDispose; + }; + + /** + * Disposes all disposables in the group and removes them from the group. + */ + CompositeDisposablePrototype.dispose = function () { + if (!this.isDisposed) { + this.isDisposed = true; + var currentDisposables = this.disposables.slice(0); + this.disposables = []; + this.length = 0; + + for (var i = 0, len = currentDisposables.length; i < len; i++) { + currentDisposables[i].dispose(); + } + } + }; + + /** + * Removes and disposes all disposables from the CompositeDisposable, but does not dispose the CompositeDisposable. + */ + CompositeDisposablePrototype.clear = function () { + var currentDisposables = this.disposables.slice(0); + this.disposables = []; + this.length = 0; + for (var i = 0, len = currentDisposables.length; i < len; i++) { + currentDisposables[i].dispose(); + } + }; + + /** + * Determines whether the CompositeDisposable contains a specific disposable. + * @param {Mixed} item Disposable to search for. + * @returns {Boolean} true if the disposable was found; otherwise, false. + */ + CompositeDisposablePrototype.contains = function (item) { + return this.disposables.indexOf(item) !== -1; + }; + + /** + * Converts the existing CompositeDisposable to an array of disposables + * @returns {Array} An array of disposable objects. + */ + CompositeDisposablePrototype.toArray = function () { + return this.disposables.slice(0); + }; + + /** + * Provides a set of static methods for creating Disposables. + * + * @constructor + * @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once. + */ + var Disposable = Rx.Disposable = function (action) { + this.isDisposed = false; + this.action = action || noop; + }; + + /** Performs the task of cleaning up resources. */ + Disposable.prototype.dispose = function () { + if (!this.isDisposed) { + this.action(); + this.isDisposed = true; + } + }; + + /** + * Creates a disposable object that invokes the specified action when disposed. + * @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once. + * @return {Disposable} The disposable object that runs the given action upon disposal. + */ + var disposableCreate = Disposable.create = function (action) { return new Disposable(action); }; + + /** + * Gets the disposable that does nothing when disposed. + */ + var disposableEmpty = Disposable.empty = { dispose: noop }; + + var BooleanDisposable = (function () { + function BooleanDisposable (isSingle) { + this.isSingle = isSingle; + this.isDisposed = false; + this.current = null; + } + + var booleanDisposablePrototype = BooleanDisposable.prototype; + + /** + * Gets the underlying disposable. + * @return The underlying disposable. + */ + booleanDisposablePrototype.getDisposable = function () { + return this.current; + }; + + /** + * Sets the underlying disposable. + * @param {Disposable} value The new underlying disposable. + */ + booleanDisposablePrototype.setDisposable = function (value) { + if (this.current && this.isSingle) { + throw new Error('Disposable has already been assigned'); + } + + var shouldDispose = this.isDisposed, old; + if (!shouldDispose) { + old = this.current; + this.current = value; + } + if (old) { + old.dispose(); + } + if (shouldDispose && value) { + value.dispose(); + } + }; + + /** + * Disposes the underlying disposable as well as all future replacements. + */ + booleanDisposablePrototype.dispose = function () { + var old; + if (!this.isDisposed) { + this.isDisposed = true; + old = this.current; + this.current = null; + } + if (old) { + old.dispose(); + } + }; + + return BooleanDisposable; + }()); + + /** + * Represents a disposable resource which only allows a single assignment of its underlying disposable resource. + * If an underlying disposable resource has already been set, future attempts to set the underlying disposable resource will throw an Error. + */ + var SingleAssignmentDisposable = Rx.SingleAssignmentDisposable = (function (super_) { + inherits(SingleAssignmentDisposable, super_); + + function SingleAssignmentDisposable() { + super_.call(this, true); + } + + return SingleAssignmentDisposable; + }(BooleanDisposable)); + + /** + * Represents a disposable resource whose underlying disposable resource can be replaced by another disposable resource, causing automatic disposal of the previous underlying disposable resource. + */ + var SerialDisposable = Rx.SerialDisposable = (function (super_) { + inherits(SerialDisposable, super_); + + function SerialDisposable() { + super_.call(this, false); + } + + return SerialDisposable; + }(BooleanDisposable)); + + /** + * Represents a disposable resource that only disposes its underlying disposable resource when all dependent disposable objects have been disposed. + */ + var RefCountDisposable = Rx.RefCountDisposable = (function () { + + function InnerDisposable(disposable) { + this.disposable = disposable; + this.disposable.count++; + this.isInnerDisposed = false; + } + + InnerDisposable.prototype.dispose = function () { + if (!this.disposable.isDisposed) { + if (!this.isInnerDisposed) { + this.isInnerDisposed = true; + this.disposable.count--; + if (this.disposable.count === 0 && this.disposable.isPrimaryDisposed) { + this.disposable.isDisposed = true; + this.disposable.underlyingDisposable.dispose(); + } + } + } + }; + + /** + * Initializes a new instance of the RefCountDisposable with the specified disposable. + * @constructor + * @param {Disposable} disposable Underlying disposable. + */ + function RefCountDisposable(disposable) { + this.underlyingDisposable = disposable; + this.isDisposed = false; + this.isPrimaryDisposed = false; + this.count = 0; + } + + /** + * Disposes the underlying disposable only when all dependent disposables have been disposed + */ + RefCountDisposable.prototype.dispose = function () { + if (!this.isDisposed) { + if (!this.isPrimaryDisposed) { + this.isPrimaryDisposed = true; + if (this.count === 0) { + this.isDisposed = true; + this.underlyingDisposable.dispose(); + } + } + } + }; + + /** + * Returns a dependent disposable that when disposed decreases the refcount on the underlying disposable. + * @returns {Disposable} A dependent disposable contributing to the reference count that manages the underlying disposable's lifetime. + */ + RefCountDisposable.prototype.getDisposable = function () { + return this.isDisposed ? disposableEmpty : new InnerDisposable(this); + }; + + return RefCountDisposable; + })(); + + function ScheduledDisposable(scheduler, disposable) { + this.scheduler = scheduler; + this.disposable = disposable; + this.isDisposed = false; + } + + ScheduledDisposable.prototype.dispose = function () { + var parent = this; + this.scheduler.schedule(function () { + if (!parent.isDisposed) { + parent.isDisposed = true; + parent.disposable.dispose(); + } + }); + }; + + var ScheduledItem = Rx.internals.ScheduledItem = function (scheduler, state, action, dueTime, comparer) { + this.scheduler = scheduler; + this.state = state; + this.action = action; + this.dueTime = dueTime; + this.comparer = comparer || defaultSubComparer; + this.disposable = new SingleAssignmentDisposable(); + } + + ScheduledItem.prototype.invoke = function () { + this.disposable.setDisposable(this.invokeCore()); + }; + + ScheduledItem.prototype.compareTo = function (other) { + return this.comparer(this.dueTime, other.dueTime); + }; + + ScheduledItem.prototype.isCancelled = function () { + return this.disposable.isDisposed; + }; + + ScheduledItem.prototype.invokeCore = function () { + return this.action(this.scheduler, this.state); + }; + + /** Provides a set of static properties to access commonly used schedulers. */ + var Scheduler = Rx.Scheduler = (function () { + + /** + * @constructor + * @private + */ + function Scheduler(now, schedule, scheduleRelative, scheduleAbsolute) { + this.now = now; + this._schedule = schedule; + this._scheduleRelative = scheduleRelative; + this._scheduleAbsolute = scheduleAbsolute; + } + + function invokeRecImmediate(scheduler, pair) { + var state = pair.first, action = pair.second, group = new CompositeDisposable(), + recursiveAction = function (state1) { + action(state1, function (state2) { + var isAdded = false, isDone = false, + d = scheduler.scheduleWithState(state2, function (scheduler1, state3) { + if (isAdded) { + group.remove(d); + } else { + isDone = true; + } + recursiveAction(state3); + return disposableEmpty; + }); + if (!isDone) { + group.add(d); + isAdded = true; + } + }); + }; + recursiveAction(state); + return group; + } + + function invokeRecDate(scheduler, pair, method) { + var state = pair.first, action = pair.second, group = new CompositeDisposable(), + recursiveAction = function (state1) { + action(state1, function (state2, dueTime1) { + var isAdded = false, isDone = false, + d = scheduler[method].call(scheduler, state2, dueTime1, function (scheduler1, state3) { + if (isAdded) { + group.remove(d); + } else { + isDone = true; + } + recursiveAction(state3); + return disposableEmpty; + }); + if (!isDone) { + group.add(d); + isAdded = true; + } + }); + }; + recursiveAction(state); + return group; + } + + function invokeAction(scheduler, action) { + action(); + return disposableEmpty; + } + + var schedulerProto = Scheduler.prototype; + + /** + * Returns a scheduler that wraps the original scheduler, adding exception handling for scheduled actions. + * @param {Function} handler Handler that's run if an exception is caught. The exception will be rethrown if the handler returns false. + * @returns {Scheduler} Wrapper around the original scheduler, enforcing exception handling. + */ + schedulerProto.catchException = schedulerProto['catch'] = function (handler) { + return new CatchScheduler(this, handler); + }; + + /** + * Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation. + * @param {Number} period Period for running the work periodically. + * @param {Function} action Action to be executed. + * @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort). + */ + schedulerProto.schedulePeriodic = function (period, action) { + return this.schedulePeriodicWithState(null, period, function () { + action(); + }); + }; + + /** + * Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation. + * @param {Mixed} state Initial state passed to the action upon the first iteration. + * @param {Number} period Period for running the work periodically. + * @param {Function} action Action to be executed, potentially updating the state. + * @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort). + */ + schedulerProto.schedulePeriodicWithState = function (state, period, action) { + var s = state, id = setInterval(function () { + s = action(s); + }, period); + return disposableCreate(function () { + clearInterval(id); + }); + }; + + /** + * Schedules an action to be executed. + * @param {Function} action Action to execute. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.schedule = function (action) { + return this._schedule(action, invokeAction); + }; + + /** + * Schedules an action to be executed. + * @param state State passed to the action to be executed. + * @param {Function} action Action to be executed. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleWithState = function (state, action) { + return this._schedule(state, action); + }; + + /** + * Schedules an action to be executed after the specified relative due time. + * @param {Function} action Action to execute. + * @param {Number} dueTime Relative time after which to execute the action. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleWithRelative = function (dueTime, action) { + return this._scheduleRelative(action, dueTime, invokeAction); + }; + + /** + * Schedules an action to be executed after dueTime. + * @param state State passed to the action to be executed. + * @param {Function} action Action to be executed. + * @param {Number} dueTime Relative time after which to execute the action. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleWithRelativeAndState = function (state, dueTime, action) { + return this._scheduleRelative(state, dueTime, action); + }; + + /** + * Schedules an action to be executed at the specified absolute due time. + * @param {Function} action Action to execute. + * @param {Number} dueTime Absolute time at which to execute the action. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleWithAbsolute = function (dueTime, action) { + return this._scheduleAbsolute(action, dueTime, invokeAction); + }; + + /** + * Schedules an action to be executed at dueTime. + * @param {Mixed} state State passed to the action to be executed. + * @param {Function} action Action to be executed. + * @param {Number}dueTime Absolute time at which to execute the action. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleWithAbsoluteAndState = function (state, dueTime, action) { + return this._scheduleAbsolute(state, dueTime, action); + }; + + /** + * Schedules an action to be executed recursively. + * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleRecursive = function (action) { + return this.scheduleRecursiveWithState(action, function (_action, self) { + _action(function () { + self(_action); + }); + }); + }; + + /** + * Schedules an action to be executed recursively. + * @param {Mixed} state State passed to the action to be executed. + * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in recursive invocation state. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleRecursiveWithState = function (state, action) { + return this.scheduleWithState({ first: state, second: action }, function (s, p) { + return invokeRecImmediate(s, p); + }); + }; + + /** + * Schedules an action to be executed recursively after a specified relative due time. + * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified relative time. + * @param {Number}dueTime Relative time after which to execute the action for the first time. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleRecursiveWithRelative = function (dueTime, action) { + return this.scheduleRecursiveWithRelativeAndState(action, dueTime, function (_action, self) { + _action(function (dt) { + self(_action, dt); + }); + }); + }; + + /** + * Schedules an action to be executed recursively after a specified relative due time. + * @param {Mixed} state State passed to the action to be executed. + * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state. + * @param {Number}dueTime Relative time after which to execute the action for the first time. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleRecursiveWithRelativeAndState = function (state, dueTime, action) { + return this._scheduleRelative({ first: state, second: action }, dueTime, function (s, p) { + return invokeRecDate(s, p, 'scheduleWithRelativeAndState'); + }); + }; + + /** + * Schedules an action to be executed recursively at a specified absolute due time. + * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified absolute time. + * @param {Number}dueTime Absolute time at which to execute the action for the first time. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleRecursiveWithAbsolute = function (dueTime, action) { + return this.scheduleRecursiveWithAbsoluteAndState(action, dueTime, function (_action, self) { + _action(function (dt) { + self(_action, dt); + }); + }); + }; + + /** + * Schedules an action to be executed recursively at a specified absolute due time. + * @param {Mixed} state State passed to the action to be executed. + * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state. + * @param {Number}dueTime Absolute time at which to execute the action for the first time. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleRecursiveWithAbsoluteAndState = function (state, dueTime, action) { + return this._scheduleAbsolute({ first: state, second: action }, dueTime, function (s, p) { + return invokeRecDate(s, p, 'scheduleWithAbsoluteAndState'); + }); + }; + + /** Gets the current time according to the local machine's system clock. */ + Scheduler.now = defaultNow; + + /** + * Normalizes the specified TimeSpan value to a positive value. + * @param {Number} timeSpan The time span value to normalize. + * @returns {Number} The specified TimeSpan value if it is zero or positive; otherwise, 0 + */ + Scheduler.normalize = function (timeSpan) { + if (timeSpan < 0) { + timeSpan = 0; + } + return timeSpan; + }; + + return Scheduler; + }()); + + var normalizeTime = Scheduler.normalize; + + var SchedulePeriodicRecursive = Rx.internals.SchedulePeriodicRecursive = (function () { + function tick(command, recurse) { + recurse(0, this._period); + try { + this._state = this._action(this._state); + } catch (e) { + this._cancel.dispose(); + throw e; + } + } + + function SchedulePeriodicRecursive(scheduler, state, period, action) { + this._scheduler = scheduler; + this._state = state; + this._period = period; + this._action = action; + } + + SchedulePeriodicRecursive.prototype.start = function () { + var d = new SingleAssignmentDisposable(); + this._cancel = d; + d.setDisposable(this._scheduler.scheduleRecursiveWithRelativeAndState(0, this._period, tick.bind(this))); + + return d; + }; + + return SchedulePeriodicRecursive; + }()); + + /** + * Gets a scheduler that schedules work immediately on the current thread. + */ + var immediateScheduler = Scheduler.immediate = (function () { + + function scheduleNow(state, action) { return action(this, state); } + + function scheduleRelative(state, dueTime, action) { + var dt = normalizeTime(dt); + while (dt - this.now() > 0) { } + return action(this, state); + } + + function scheduleAbsolute(state, dueTime, action) { + return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); + } + + return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); + }()); + + /** + * Gets a scheduler that schedules work as soon as possible on the current thread. + */ + var currentThreadScheduler = Scheduler.currentThread = (function () { + var queue; + + function runTrampoline (q) { + var item; + while (q.length > 0) { + item = q.dequeue(); + if (!item.isCancelled()) { + // Note, do not schedule blocking work! + while (item.dueTime - Scheduler.now() > 0) { + } + if (!item.isCancelled()) { + item.invoke(); + } + } + } + } + + function scheduleNow(state, action) { + return this.scheduleWithRelativeAndState(state, 0, action); + } + + function scheduleRelative(state, dueTime, action) { + var dt = this.now() + Scheduler.normalize(dueTime), + si = new ScheduledItem(this, state, action, dt), + t; + if (!queue) { + queue = new PriorityQueue(4); + queue.enqueue(si); + try { + runTrampoline(queue); + } catch (e) { + throw e; + } finally { + queue = null; + } + } else { + queue.enqueue(si); + } + return si.disposable; + } + + function scheduleAbsolute(state, dueTime, action) { + return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); + } + + var currentScheduler = new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); + currentScheduler.scheduleRequired = function () { return queue === null; }; + currentScheduler.ensureTrampoline = function (action) { + if (queue === null) { + return this.schedule(action); + } else { + return action(); + } + }; + + return currentScheduler; + }()); + + + var scheduleMethod, clearMethod = noop; + (function () { + + var reNative = RegExp('^' + + String(toString) + .replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + .replace(/toString| for [^\]]+/g, '.*?') + '$' + ); + + var setImmediate = typeof (setImmediate = freeGlobal && moduleExports && freeGlobal.setImmediate) == 'function' && + !reNative.test(setImmediate) && setImmediate, + clearImmediate = typeof (clearImmediate = freeGlobal && moduleExports && freeGlobal.clearImmediate) == 'function' && + !reNative.test(clearImmediate) && clearImmediate; + + function postMessageSupported () { + // Ensure not in a worker + if (!root.postMessage || root.importScripts) { return false; } + var isAsync = false, + oldHandler = root.onmessage; + // Test for async + root.onmessage = function () { isAsync = true; }; + root.postMessage('','*'); + root.onmessage = oldHandler; + + return isAsync; + } + + // Use in order, nextTick, setImmediate, postMessage, MessageChannel, script readystatechanged, setTimeout + if (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]') { + scheduleMethod = process.nextTick; + } else if (typeof setImmediate === 'function') { + scheduleMethod = setImmediate; + clearMethod = clearImmediate; + } else if (postMessageSupported()) { + var MSG_PREFIX = 'ms.rx.schedule' + Math.random(), + tasks = {}, + taskId = 0; + + function onGlobalPostMessage(event) { + // Only if we're a match to avoid any other global events + if (typeof event.data === 'string' && event.data.substring(0, MSG_PREFIX.length) === MSG_PREFIX) { + var handleId = event.data.substring(MSG_PREFIX.length), + action = tasks[handleId]; + action(); + delete tasks[handleId]; + } + } + + if (root.addEventListener) { + root.addEventListener('message', onGlobalPostMessage, false); + } else { + root.attachEvent('onmessage', onGlobalPostMessage, false); + } + + scheduleMethod = function (action) { + var currentId = taskId++; + tasks[currentId] = action; + root.postMessage(MSG_PREFIX + currentId, '*'); + }; + } else if (!!root.MessageChannel) { + var channel = new root.MessageChannel(), + channelTasks = {}, + channelTaskId = 0; + + channel.port1.onmessage = function (event) { + var id = event.data, + action = channelTasks[id]; + action(); + delete channelTasks[id]; + }; + + scheduleMethod = function (action) { + var id = channelTaskId++; + channelTasks[id] = action; + channel.port2.postMessage(id); + }; + } else if ('document' in root && 'onreadystatechange' in root.document.createElement('script')) { + + scheduleMethod = function (action) { + var scriptElement = root.document.createElement('script'); + scriptElement.onreadystatechange = function () { + action(); + scriptElement.onreadystatechange = null; + scriptElement.parentNode.removeChild(scriptElement); + scriptElement = null; + }; + root.document.documentElement.appendChild(scriptElement); + }; + + } else { + scheduleMethod = function (action) { return setTimeout(action, 0); }; + clearMethod = clearTimeout; + } + }()); + + /** + * Gets a scheduler that schedules work via a timed callback based upon platform. + */ + var timeoutScheduler = Scheduler.timeout = (function () { + + function scheduleNow(state, action) { + var scheduler = this, + disposable = new SingleAssignmentDisposable(); + var id = scheduleMethod(function () { + if (!disposable.isDisposed) { + disposable.setDisposable(action(scheduler, state)); + } + }); + return new CompositeDisposable(disposable, disposableCreate(function () { + clearMethod(id); + })); + } + + function scheduleRelative(state, dueTime, action) { + var scheduler = this, + dt = Scheduler.normalize(dueTime); + if (dt === 0) { + return scheduler.scheduleWithState(state, action); + } + var disposable = new SingleAssignmentDisposable(); + var id = setTimeout(function () { + if (!disposable.isDisposed) { + disposable.setDisposable(action(scheduler, state)); + } + }, dt); + return new CompositeDisposable(disposable, disposableCreate(function () { + clearTimeout(id); + })); + } + + function scheduleAbsolute(state, dueTime, action) { + return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); + } + + return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); + })(); + + /** @private */ + var CatchScheduler = (function (_super) { + + function localNow() { + return this._scheduler.now(); + } + + function scheduleNow(state, action) { + return this._scheduler.scheduleWithState(state, this._wrap(action)); + } + + function scheduleRelative(state, dueTime, action) { + return this._scheduler.scheduleWithRelativeAndState(state, dueTime, this._wrap(action)); + } + + function scheduleAbsolute(state, dueTime, action) { + return this._scheduler.scheduleWithAbsoluteAndState(state, dueTime, this._wrap(action)); + } + + inherits(CatchScheduler, _super); + + /** @private */ + function CatchScheduler(scheduler, handler) { + this._scheduler = scheduler; + this._handler = handler; + this._recursiveOriginal = null; + this._recursiveWrapper = null; + _super.call(this, localNow, scheduleNow, scheduleRelative, scheduleAbsolute); + } + + /** @private */ + CatchScheduler.prototype._clone = function (scheduler) { + return new CatchScheduler(scheduler, this._handler); + }; + + /** @private */ + CatchScheduler.prototype._wrap = function (action) { + var parent = this; + return function (self, state) { + try { + return action(parent._getRecursiveWrapper(self), state); + } catch (e) { + if (!parent._handler(e)) { throw e; } + return disposableEmpty; + } + }; + }; + + /** @private */ + CatchScheduler.prototype._getRecursiveWrapper = function (scheduler) { + if (this._recursiveOriginal !== scheduler) { + this._recursiveOriginal = scheduler; + var wrapper = this._clone(scheduler); + wrapper._recursiveOriginal = scheduler; + wrapper._recursiveWrapper = wrapper; + this._recursiveWrapper = wrapper; + } + return this._recursiveWrapper; + }; + + /** @private */ + CatchScheduler.prototype.schedulePeriodicWithState = function (state, period, action) { + var self = this, failed = false, d = new SingleAssignmentDisposable(); + + d.setDisposable(this._scheduler.schedulePeriodicWithState(state, period, function (state1) { + if (failed) { return null; } + try { + return action(state1); + } catch (e) { + failed = true; + if (!self._handler(e)) { throw e; } + d.dispose(); + return null; + } + })); + + return d; + }; + + return CatchScheduler; + }(Scheduler)); + + /** + * Represents a notification to an observer. + */ + var Notification = Rx.Notification = (function () { + function Notification(kind, hasValue) { + this.hasValue = hasValue == null ? false : hasValue; + this.kind = kind; + } + + var NotificationPrototype = Notification.prototype; + + /** + * Invokes the delegate corresponding to the notification or the observer's method corresponding to the notification and returns the produced result. + * + * @memberOf Notification + * @param {Any} observerOrOnNext Delegate to invoke for an OnNext notification or Observer to invoke the notification on.. + * @param {Function} onError Delegate to invoke for an OnError notification. + * @param {Function} onCompleted Delegate to invoke for an OnCompleted notification. + * @returns {Any} Result produced by the observation. + */ + NotificationPrototype.accept = function (observerOrOnNext, onError, onCompleted) { + if (arguments.length === 1 && typeof observerOrOnNext === 'object') { + return this._acceptObservable(observerOrOnNext); + } + return this._accept(observerOrOnNext, onError, onCompleted); + }; + + /** + * Returns an observable sequence with a single notification. + * + * @memberOf Notification + * @param {Scheduler} [scheduler] Scheduler to send out the notification calls on. + * @returns {Observable} The observable sequence that surfaces the behavior of the notification upon subscription. + */ + NotificationPrototype.toObservable = function (scheduler) { + var notification = this; + scheduler || (scheduler = immediateScheduler); + return new AnonymousObservable(function (observer) { + return scheduler.schedule(function () { + notification._acceptObservable(observer); + if (notification.kind === 'N') { + observer.onCompleted(); + } + }); + }); + }; + + return Notification; + })(); + + /** + * Creates an object that represents an OnNext notification to an observer. + * @param {Any} value The value contained in the notification. + * @returns {Notification} The OnNext notification containing the value. + */ + var notificationCreateOnNext = Notification.createOnNext = (function () { + + function _accept (onNext) { + return onNext(this.value); + } + + function _acceptObservable(observer) { + return observer.onNext(this.value); + } + + function toString () { + return 'OnNext(' + this.value + ')'; + } + + return function (value) { + var notification = new Notification('N', true); + notification.value = value; + notification._accept = _accept; + notification._acceptObservable = _acceptObservable; + notification.toString = toString; + return notification; + }; + }()); + + /** + * Creates an object that represents an OnError notification to an observer. + * @param {Any} error The exception contained in the notification. + * @returns {Notification} The OnError notification containing the exception. + */ + var notificationCreateOnError = Notification.createOnError = (function () { + + function _accept (onNext, onError) { + return onError(this.exception); + } + + function _acceptObservable(observer) { + return observer.onError(this.exception); + } + + function toString () { + return 'OnError(' + this.exception + ')'; + } + + return function (exception) { + var notification = new Notification('E'); + notification.exception = exception; + notification._accept = _accept; + notification._acceptObservable = _acceptObservable; + notification.toString = toString; + return notification; + }; + }()); + + /** + * Creates an object that represents an OnCompleted notification to an observer. + * @returns {Notification} The OnCompleted notification. + */ + var notificationCreateOnCompleted = Notification.createOnCompleted = (function () { + + function _accept (onNext, onError, onCompleted) { + return onCompleted(); + } + + function _acceptObservable(observer) { + return observer.onCompleted(); + } + + function toString () { + return 'OnCompleted()'; + } + + return function () { + var notification = new Notification('C'); + notification._accept = _accept; + notification._acceptObservable = _acceptObservable; + notification.toString = toString; + return notification; + }; + }()); + + var Enumerator = Rx.internals.Enumerator = function (next) { + this._next = next; + }; + + Enumerator.prototype.next = function () { + return this._next(); + }; + + Enumerator.prototype[$iterator$] = function () { return this; } + + var Enumerable = Rx.internals.Enumerable = function (iterator) { + this._iterator = iterator; + }; + + Enumerable.prototype[$iterator$] = function () { + return this._iterator(); + }; + + Enumerable.prototype.concat = function () { + var sources = this; + return new AnonymousObservable(function (observer) { + var e; + try { + e = sources[$iterator$](); + } catch(err) { + observer.onError(); + return; + } + + var isDisposed, + subscription = new SerialDisposable(); + var cancelable = immediateScheduler.scheduleRecursive(function (self) { + var currentItem; + if (isDisposed) { return; } + + try { + currentItem = e.next(); + } catch (ex) { + observer.onError(ex); + return; + } + + if (currentItem.done) { + observer.onCompleted(); + return; + } + + // Check if promise + var currentValue = currentItem.value; + isPromise(currentValue) && (currentValue = observableFromPromise(currentValue)); + + var d = new SingleAssignmentDisposable(); + subscription.setDisposable(d); + d.setDisposable(currentValue.subscribe( + observer.onNext.bind(observer), + observer.onError.bind(observer), + function () { self(); }) + ); + }); + + return new CompositeDisposable(subscription, cancelable, disposableCreate(function () { + isDisposed = true; + })); + }); + }; + + Enumerable.prototype.catchException = function () { + var sources = this; + return new AnonymousObservable(function (observer) { + var e; + try { + e = sources[$iterator$](); + } catch(err) { + observer.onError(); + return; + } + + var isDisposed, + lastException, + subscription = new SerialDisposable(); + var cancelable = immediateScheduler.scheduleRecursive(function (self) { + if (isDisposed) { return; } + + var currentItem; + try { + currentItem = e.next(); + } catch (ex) { + observer.onError(ex); + return; + } + + if (currentItem.done) { + if (lastException) { + observer.onError(lastException); + } else { + observer.onCompleted(); + } + return; + } + + // Check if promise + var currentValue = currentItem.value; + isPromise(currentValue) && (currentValue = observableFromPromise(currentValue)); + + var d = new SingleAssignmentDisposable(); + subscription.setDisposable(d); + d.setDisposable(currentValue.subscribe( + observer.onNext.bind(observer), + function (exn) { + lastException = exn; + self(); + }, + observer.onCompleted.bind(observer))); + }); + return new CompositeDisposable(subscription, cancelable, disposableCreate(function () { + isDisposed = true; + })); + }); + }; + + var enumerableRepeat = Enumerable.repeat = function (value, repeatCount) { + if (repeatCount == null) { repeatCount = -1; } + return new Enumerable(function () { + var left = repeatCount; + return new Enumerator(function () { + if (left === 0) { return doneEnumerator; } + if (left > 0) { left--; } + return { done: false, value: value }; + }); + }); + }; + + var enumerableFor = Enumerable.forEach = function (source, selector, thisArg) { + selector || (selector = identity); + return new Enumerable(function () { + var index = -1; + return new Enumerator( + function () { + return ++index < source.length ? + { done: false, value: selector.call(thisArg, source[index], index, source) } : + doneEnumerator; + }); + }); + }; + + /** + * Supports push-style iteration over an observable sequence. + */ + var Observer = Rx.Observer = function () { }; + + /** + * Creates a notification callback from an observer. + * + * @param observer Observer object. + * @returns The action that forwards its input notification to the underlying observer. + */ + Observer.prototype.toNotifier = function () { + var observer = this; + return function (n) { + return n.accept(observer); + }; + }; + + /** + * Hides the identity of an observer. + + * @returns An observer that hides the identity of the specified observer. + */ + Observer.prototype.asObserver = function () { + return new AnonymousObserver(this.onNext.bind(this), this.onError.bind(this), this.onCompleted.bind(this)); + }; + + /** + * Checks access to the observer for grammar violations. This includes checking for multiple OnError or OnCompleted calls, as well as reentrancy in any of the observer methods. + * If a violation is detected, an Error is thrown from the offending observer method call. + * + * @returns An observer that checks callbacks invocations against the observer grammar and, if the checks pass, forwards those to the specified observer. + */ + Observer.prototype.checked = function () { return new CheckedObserver(this); }; + + /** + * Creates an observer from the specified OnNext, along with optional OnError, and OnCompleted actions. + * + * @static + * @memberOf Observer + * @param {Function} [onNext] Observer's OnNext action implementation. + * @param {Function} [onError] Observer's OnError action implementation. + * @param {Function} [onCompleted] Observer's OnCompleted action implementation. + * @returns {Observer} The observer object implemented using the given actions. + */ + var observerCreate = Observer.create = function (onNext, onError, onCompleted) { + onNext || (onNext = noop); + onError || (onError = defaultError); + onCompleted || (onCompleted = noop); + return new AnonymousObserver(onNext, onError, onCompleted); + }; + + /** + * Creates an observer from a notification callback. + * + * @static + * @memberOf Observer + * @param {Function} handler Action that handles a notification. + * @returns The observer object that invokes the specified handler using a notification corresponding to each message it receives. + */ + Observer.fromNotifier = function (handler) { + return new AnonymousObserver(function (x) { + return handler(notificationCreateOnNext(x)); + }, function (exception) { + return handler(notificationCreateOnError(exception)); + }, function () { + return handler(notificationCreateOnCompleted()); + }); + }; + + /** + * Schedules the invocation of observer methods on the given scheduler. + * @param {Scheduler} scheduler Scheduler to schedule observer messages on. + * @returns {Observer} Observer whose messages are scheduled on the given scheduler. + */ + Observer.notifyOn = function (scheduler) { + return new ObserveOnObserver(scheduler, this); + }; + + /** + * Abstract base class for implementations of the Observer class. + * This base class enforces the grammar of observers where OnError and OnCompleted are terminal messages. + */ + var AbstractObserver = Rx.internals.AbstractObserver = (function (_super) { + inherits(AbstractObserver, _super); + + /** + * Creates a new observer in a non-stopped state. + * + * @constructor + */ + function AbstractObserver() { + this.isStopped = false; + _super.call(this); + } + + /** + * Notifies the observer of a new element in the sequence. + * + * @memberOf AbstractObserver + * @param {Any} value Next element in the sequence. + */ + AbstractObserver.prototype.onNext = function (value) { + if (!this.isStopped) { + this.next(value); + } + }; + + /** + * Notifies the observer that an exception has occurred. + * + * @memberOf AbstractObserver + * @param {Any} error The error that has occurred. + */ + AbstractObserver.prototype.onError = function (error) { + if (!this.isStopped) { + this.isStopped = true; + this.error(error); + } + }; + + /** + * Notifies the observer of the end of the sequence. + */ + AbstractObserver.prototype.onCompleted = function () { + if (!this.isStopped) { + this.isStopped = true; + this.completed(); + } + }; + + /** + * Disposes the observer, causing it to transition to the stopped state. + */ + AbstractObserver.prototype.dispose = function () { + this.isStopped = true; + }; + + AbstractObserver.prototype.fail = function (e) { + if (!this.isStopped) { + this.isStopped = true; + this.error(e); + return true; + } + + return false; + }; + + return AbstractObserver; + }(Observer)); + + /** + * Class to create an Observer instance from delegate-based implementations of the on* methods. + */ + var AnonymousObserver = Rx.AnonymousObserver = (function (_super) { + inherits(AnonymousObserver, _super); + + /** + * Creates an observer from the specified OnNext, OnError, and OnCompleted actions. + * @param {Any} onNext Observer's OnNext action implementation. + * @param {Any} onError Observer's OnError action implementation. + * @param {Any} onCompleted Observer's OnCompleted action implementation. + */ + function AnonymousObserver(onNext, onError, onCompleted) { + _super.call(this); + this._onNext = onNext; + this._onError = onError; + this._onCompleted = onCompleted; + } + + /** + * Calls the onNext action. + * @param {Any} value Next element in the sequence. + */ + AnonymousObserver.prototype.next = function (value) { + this._onNext(value); + }; + + /** + * Calls the onError action. + * @param {Any} error The error that has occurred. + */ + AnonymousObserver.prototype.error = function (exception) { + this._onError(exception); + }; + + /** + * Calls the onCompleted action. + */ + AnonymousObserver.prototype.completed = function () { + this._onCompleted(); + }; + + return AnonymousObserver; + }(AbstractObserver)); + + var CheckedObserver = (function (_super) { + inherits(CheckedObserver, _super); + + function CheckedObserver(observer) { + _super.call(this); + this._observer = observer; + this._state = 0; // 0 - idle, 1 - busy, 2 - done + } + + var CheckedObserverPrototype = CheckedObserver.prototype; + + CheckedObserverPrototype.onNext = function (value) { + this.checkAccess(); + try { + this._observer.onNext(value); + } catch (e) { + throw e; + } finally { + this._state = 0; + } + }; + + CheckedObserverPrototype.onError = function (err) { + this.checkAccess(); + try { + this._observer.onError(err); + } catch (e) { + throw e; + } finally { + this._state = 2; + } + }; + + CheckedObserverPrototype.onCompleted = function () { + this.checkAccess(); + try { + this._observer.onCompleted(); + } catch (e) { + throw e; + } finally { + this._state = 2; + } + }; + + CheckedObserverPrototype.checkAccess = function () { + if (this._state === 1) { throw new Error('Re-entrancy detected'); } + if (this._state === 2) { throw new Error('Observer completed'); } + if (this._state === 0) { this._state = 1; } + }; + + return CheckedObserver; + }(Observer)); + + var ScheduledObserver = Rx.internals.ScheduledObserver = (function (_super) { + inherits(ScheduledObserver, _super); + + function ScheduledObserver(scheduler, observer) { + _super.call(this); + this.scheduler = scheduler; + this.observer = observer; + this.isAcquired = false; + this.hasFaulted = false; + this.queue = []; + this.disposable = new SerialDisposable(); + } + + ScheduledObserver.prototype.next = function (value) { + var self = this; + this.queue.push(function () { + self.observer.onNext(value); + }); + }; + + ScheduledObserver.prototype.error = function (exception) { + var self = this; + this.queue.push(function () { + self.observer.onError(exception); + }); + }; + + ScheduledObserver.prototype.completed = function () { + var self = this; + this.queue.push(function () { + self.observer.onCompleted(); + }); + }; + + ScheduledObserver.prototype.ensureActive = function () { + var isOwner = false, parent = this; + if (!this.hasFaulted && this.queue.length > 0) { + isOwner = !this.isAcquired; + this.isAcquired = true; + } + if (isOwner) { + this.disposable.setDisposable(this.scheduler.scheduleRecursive(function (self) { + var work; + if (parent.queue.length > 0) { + work = parent.queue.shift(); + } else { + parent.isAcquired = false; + return; + } + try { + work(); + } catch (ex) { + parent.queue = []; + parent.hasFaulted = true; + throw ex; + } + self(); + })); + } + }; + + ScheduledObserver.prototype.dispose = function () { + _super.prototype.dispose.call(this); + this.disposable.dispose(); + }; + + return ScheduledObserver; + }(AbstractObserver)); + + /** @private */ + var ObserveOnObserver = (function (_super) { + inherits(ObserveOnObserver, _super); + + /** @private */ + function ObserveOnObserver() { + _super.apply(this, arguments); + } + + /** @private */ + ObserveOnObserver.prototype.next = function (value) { + _super.prototype.next.call(this, value); + this.ensureActive(); + }; + + /** @private */ + ObserveOnObserver.prototype.error = function (e) { + _super.prototype.error.call(this, e); + this.ensureActive(); + }; + + /** @private */ + ObserveOnObserver.prototype.completed = function () { + _super.prototype.completed.call(this); + this.ensureActive(); + }; + + return ObserveOnObserver; + })(ScheduledObserver); + + var observableProto; + + /** + * Represents a push-style collection. + */ + var Observable = Rx.Observable = (function () { + + function Observable(subscribe) { + this._subscribe = subscribe; + } + + observableProto = Observable.prototype; + + /** + * Subscribes an observer to the observable sequence. + * + * @example + * 1 - source.subscribe(); + * 2 - source.subscribe(observer); + * 3 - source.subscribe(function (x) { console.log(x); }); + * 4 - source.subscribe(function (x) { console.log(x); }, function (err) { console.log(err); }); + * 5 - source.subscribe(function (x) { console.log(x); }, function (err) { console.log(err); }, function () { console.log('done'); }); + * @param {Mixed} [observerOrOnNext] The object that is to receive notifications or an action to invoke for each element in the observable sequence. + * @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence. + * @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence. + * @returns {Diposable} The source sequence whose subscriptions and unsubscriptions happen on the specified scheduler. + */ + observableProto.subscribe = observableProto.forEach = function (observerOrOnNext, onError, onCompleted) { + var subscriber = typeof observerOrOnNext === 'object' ? + observerOrOnNext : + observerCreate(observerOrOnNext, onError, onCompleted); + + return this._subscribe(subscriber); + }; + + return Observable; + })(); + + /** + * Wraps the source sequence in order to run its observer callbacks on the specified scheduler. + * + * This only invokes observer callbacks on a scheduler. In case the subscription and/or unsubscription actions have side-effects + * that require to be run on a scheduler, use subscribeOn. + * + * @param {Scheduler} scheduler Scheduler to notify observers on. + * @returns {Observable} The source sequence whose observations happen on the specified scheduler. + */ + observableProto.observeOn = function (scheduler) { + var source = this; + return new AnonymousObservable(function (observer) { + return source.subscribe(new ObserveOnObserver(scheduler, observer)); + }); + }; + + /** + * Wraps the source sequence in order to run its subscription and unsubscription logic on the specified scheduler. This operation is not commonly used; + * see the remarks section for more information on the distinction between subscribeOn and observeOn. + + * This only performs the side-effects of subscription and unsubscription on the specified scheduler. In order to invoke observer + * callbacks on a scheduler, use observeOn. + + * @param {Scheduler} scheduler Scheduler to perform subscription and unsubscription actions on. + * @returns {Observable} The source sequence whose subscriptions and unsubscriptions happen on the specified scheduler. + */ + observableProto.subscribeOn = function (scheduler) { + var source = this; + return new AnonymousObservable(function (observer) { + var m = new SingleAssignmentDisposable(), d = new SerialDisposable(); + d.setDisposable(m); + m.setDisposable(scheduler.schedule(function () { + d.setDisposable(new ScheduledDisposable(scheduler, source.subscribe(observer))); + })); + return d; + }); + }; + + /** + * Converts a Promise to an Observable sequence + * @param {Promise} An ES6 Compliant promise. + * @returns {Observable} An Observable sequence which wraps the existing promise success and failure. + */ + var observableFromPromise = Observable.fromPromise = function (promise) { + return new AnonymousObservable(function (observer) { + promise.then( + function (value) { + observer.onNext(value); + observer.onCompleted(); + }, + function (reason) { + observer.onError(reason); + }); + + return function () { + if (promise && promise.abort) { + promise.abort(); + } + } + }); + }; + /* + * Converts an existing observable sequence to an ES6 Compatible Promise + * @example + * var promise = Rx.Observable.return(42).toPromise(RSVP.Promise); + * + * // With config + * Rx.config.Promise = RSVP.Promise; + * var promise = Rx.Observable.return(42).toPromise(); + * @param {Function} [promiseCtor] The constructor of the promise. If not provided, it looks for it in Rx.config.Promise. + * @returns {Promise} An ES6 compatible promise with the last value from the observable sequence. + */ + observableProto.toPromise = function (promiseCtor) { + promiseCtor || (promiseCtor = Rx.config.Promise); + if (!promiseCtor) { + throw new Error('Promise type not provided nor in Rx.config.Promise'); + } + var source = this; + return new promiseCtor(function (resolve, reject) { + // No cancellation can be done + var value, hasValue = false; + source.subscribe(function (v) { + value = v; + hasValue = true; + }, function (err) { + reject(err); + }, function () { + if (hasValue) { + resolve(value); + } + }); + }); + }; + /** + * Creates a list from an observable sequence. + * @returns An observable sequence containing a single element with a list containing all the elements of the source sequence. + */ + observableProto.toArray = function () { + var self = this; + return new AnonymousObservable(function(observer) { + var arr = []; + return self.subscribe( + arr.push.bind(arr), + observer.onError.bind(observer), + function () { + observer.onNext(arr); + observer.onCompleted(); + }); + }); + }; + + /** + * Creates an observable sequence from a specified subscribe method implementation. + * + * @example + * var res = Rx.Observable.create(function (observer) { return function () { } ); + * var res = Rx.Observable.create(function (observer) { return Rx.Disposable.empty; } ); + * var res = Rx.Observable.create(function (observer) { } ); + * + * @param {Function} subscribe Implementation of the resulting observable sequence's subscribe method, returning a function that will be wrapped in a Disposable. + * @returns {Observable} The observable sequence with the specified implementation for the Subscribe method. + */ + Observable.create = Observable.createWithDisposable = function (subscribe) { + return new AnonymousObservable(subscribe); + }; + + /** + * Returns an observable sequence that invokes the specified factory function whenever a new observer subscribes. + * + * @example + * var res = Rx.Observable.defer(function () { return Rx.Observable.fromArray([1,2,3]); }); + * @param {Function} observableFactory Observable factory function to invoke for each observer that subscribes to the resulting sequence or Promise. + * @returns {Observable} An observable sequence whose observers trigger an invocation of the given observable factory function. + */ + var observableDefer = Observable.defer = function (observableFactory) { + return new AnonymousObservable(function (observer) { + var result; + try { + result = observableFactory(); + } catch (e) { + return observableThrow(e).subscribe(observer); + } + isPromise(result) && (result = observableFromPromise(result)); + return result.subscribe(observer); + }); + }; + + /** + * Returns an empty observable sequence, using the specified scheduler to send out the single OnCompleted message. + * + * @example + * var res = Rx.Observable.empty(); + * var res = Rx.Observable.empty(Rx.Scheduler.timeout); + * @param {Scheduler} [scheduler] Scheduler to send the termination call on. + * @returns {Observable} An observable sequence with no elements. + */ + var observableEmpty = Observable.empty = function (scheduler) { + scheduler || (scheduler = immediateScheduler); + return new AnonymousObservable(function (observer) { + return scheduler.schedule(function () { + observer.onCompleted(); + }); + }); + }; + + /** + * Converts an array to an observable sequence, using an optional scheduler to enumerate the array. + * + * @example + * var res = Rx.Observable.fromArray([1,2,3]); + * var res = Rx.Observable.fromArray([1,2,3], Rx.Scheduler.timeout); + * @param {Scheduler} [scheduler] Scheduler to run the enumeration of the input sequence on. + * @returns {Observable} The observable sequence whose elements are pulled from the given enumerable sequence. + */ + var observableFromArray = Observable.fromArray = function (array, scheduler) { + scheduler || (scheduler = currentThreadScheduler); + return new AnonymousObservable(function (observer) { + var count = 0, len = array.length; + return scheduler.scheduleRecursive(function (self) { + if (count < len) { + observer.onNext(array[count++]); + self(); + } else { + observer.onCompleted(); + } + }); + }); + }; + + /** + * Converts an iterable into an Observable sequence + * + * @example + * var res = Rx.Observable.fromIterable(new Map()); + * var res = Rx.Observable.fromIterable(new Set(), Rx.Scheduler.timeout); + * @param {Scheduler} [scheduler] Scheduler to run the enumeration of the input sequence on. + * @returns {Observable} The observable sequence whose elements are pulled from the given generator sequence. + */ + Observable.fromIterable = function (iterable, scheduler) { + scheduler || (scheduler = currentThreadScheduler); + return new AnonymousObservable(function (observer) { + var iterator; + try { + iterator = iterable[$iterator$](); + } catch (e) { + observer.onError(e); + return; + } + + return scheduler.scheduleRecursive(function (self) { + var next; + try { + next = iterator.next(); + } catch (err) { + observer.onError(err); + return; + } + + if (next.done) { + observer.onCompleted(); + } else { + observer.onNext(next.value); + self(); + } + }); + }); + }; + + /** + * 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) { + scheduler || (scheduler = currentThreadScheduler); + return new AnonymousObservable(function (observer) { + var first = true, state = initialState; + return scheduler.scheduleRecursive(function (self) { + var hasResult, result; + try { + if (first) { + first = false; + } else { + state = iterate(state); + } + hasResult = condition(state); + if (hasResult) { + result = resultSelector(state); + } + } catch (exception) { + observer.onError(exception); + return; + } + if (hasResult) { + observer.onNext(result); + self(); + } else { + observer.onCompleted(); + } + }); + }); + }; + + /** + * This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments. + * @example + * var res = Rx.Observable.of(1,2,3); + * @returns {Observable} The observable sequence whose elements are pulled from the given arguments. + */ + Observable.of = function () { + var len = arguments.length, args = new Array(len); + for(var i = 0; i < len; i++) { args[i] = arguments[i]; } + return observableFromArray(args); + }; + + /** + * This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments. + * @example + * var res = Rx.Observable.of(1,2,3); + * @param {Scheduler} scheduler A scheduler to use for scheduling the arguments. + * @returns {Observable} The observable sequence whose elements are pulled from the given arguments. + */ + var observableOf = Observable.ofWithScheduler = function (scheduler) { + var len = arguments.length - 1, args = new Array(len); + for(var i = 0; i < len; i++) { args[i] = arguments[i + 1]; } + return observableFromArray(args, scheduler); + }; + + /** + * Returns a non-terminating observable sequence, which can be used to denote an infinite duration (e.g. when using reactive joins). + * @returns {Observable} An observable sequence whose observers will never get called. + */ + var observableNever = Observable.never = function () { + return new AnonymousObservable(function () { + return disposableEmpty; + }); + }; + + /** + * Generates an observable sequence of integral numbers within a specified range, using the specified scheduler to send out observer messages. + * + * @example + * var res = Rx.Observable.range(0, 10); + * var res = Rx.Observable.range(0, 10, Rx.Scheduler.timeout); + * @param {Number} start The value of the first integer in the sequence. + * @param {Number} count The number of sequential integers to generate. + * @param {Scheduler} [scheduler] Scheduler to run the generator loop on. If not specified, defaults to Scheduler.currentThread. + * @returns {Observable} An observable sequence that contains a range of sequential integral numbers. + */ + Observable.range = function (start, count, scheduler) { + scheduler || (scheduler = currentThreadScheduler); + return new AnonymousObservable(function (observer) { + return scheduler.scheduleRecursiveWithState(0, function (i, self) { + if (i < count) { + observer.onNext(start + i); + self(i + 1); + } else { + observer.onCompleted(); + } + }); + }); + }; + + /** + * Generates an observable sequence that repeats the given element the specified number of times, using the specified scheduler to send out observer messages. + * + * @example + * var res = Rx.Observable.repeat(42); + * var res = Rx.Observable.repeat(42, 4); + * 3 - res = Rx.Observable.repeat(42, 4, Rx.Scheduler.timeout); + * 4 - res = Rx.Observable.repeat(42, null, Rx.Scheduler.timeout); + * @param {Mixed} value Element to repeat. + * @param {Number} repeatCount [Optiona] Number of times to repeat the element. If not specified, repeats indefinitely. + * @param {Scheduler} scheduler Scheduler to run the producer loop on. If not specified, defaults to Scheduler.immediate. + * @returns {Observable} An observable sequence that repeats the given element the specified number of times. + */ + Observable.repeat = function (value, repeatCount, scheduler) { + scheduler || (scheduler = currentThreadScheduler); + if (repeatCount == null) { + repeatCount = -1; + } + return observableReturn(value, scheduler).repeat(repeatCount); + }; + + /** + * Returns an observable sequence that contains a single element, using the specified scheduler to send out observer messages. + * There is an alias called 'just', and 'returnValue' for browsers 0) { + s = q.shift(); + subscribe(s); + } else { + activeCount--; + if (isStopped && activeCount === 0) { + observer.onCompleted(); + } + } + })); + }; + group.add(sources.subscribe(function (innerSource) { + if (activeCount < maxConcurrentOrOther) { + activeCount++; + subscribe(innerSource); + } else { + q.push(innerSource); + } + }, observer.onError.bind(observer), function () { + isStopped = true; + if (activeCount === 0) { + observer.onCompleted(); + } + })); + return group; + }); + }; + + /** + * Merges all the observable sequences into a single observable sequence. + * The scheduler is optional and if not specified, the immediate scheduler is used. + * + * @example + * 1 - merged = Rx.Observable.merge(xs, ys, zs); + * 2 - merged = Rx.Observable.merge([xs, ys, zs]); + * 3 - merged = Rx.Observable.merge(scheduler, xs, ys, zs); + * 4 - merged = Rx.Observable.merge(scheduler, [xs, ys, zs]); + * @returns {Observable} The observable sequence that merges the elements of the observable sequences. + */ + var observableMerge = Observable.merge = function () { + var scheduler, sources; + if (!arguments[0]) { + scheduler = immediateScheduler; + sources = slice.call(arguments, 1); + } else if (arguments[0].now) { + scheduler = arguments[0]; + sources = slice.call(arguments, 1); + } else { + scheduler = immediateScheduler; + sources = slice.call(arguments, 0); + } + if (Array.isArray(sources[0])) { + sources = sources[0]; + } + return observableFromArray(sources, scheduler).mergeObservable(); + }; + + /** + * Merges an observable sequence of observable sequences into an observable sequence. + * @returns {Observable} The observable sequence that merges the elements of the inner sequences. + */ + observableProto.mergeObservable = observableProto.mergeAll =function () { + var sources = this; + return new AnonymousObservable(function (observer) { + var group = new CompositeDisposable(), + isStopped = false, + m = new SingleAssignmentDisposable(); + + group.add(m); + m.setDisposable(sources.subscribe(function (innerSource) { + var innerSubscription = new SingleAssignmentDisposable(); + group.add(innerSubscription); + + // Check if Promise or Observable + if (isPromise(innerSource)) { + innerSource = observableFromPromise(innerSource); + } + + innerSubscription.setDisposable(innerSource.subscribe(function (x) { + observer.onNext(x); + }, observer.onError.bind(observer), function () { + group.remove(innerSubscription); + if (isStopped && group.length === 1) { observer.onCompleted(); } + })); + }, observer.onError.bind(observer), function () { + isStopped = true; + if (group.length === 1) { observer.onCompleted(); } + })); + return group; + }); + }; + + /** + * Continues an observable sequence that is terminated normally or by an exception with the next observable sequence. + * @param {Observable} second Second observable sequence used to produce results after the first sequence terminates. + * @returns {Observable} An observable sequence that concatenates the first and second sequence, even if the first sequence terminates exceptionally. + */ + observableProto.onErrorResumeNext = function (second) { + if (!second) { + throw new Error('Second observable is required'); + } + return onErrorResumeNext([this, second]); + }; + + /** + * Continues an observable sequence that is terminated normally or by an exception with the next observable sequence. + * + * @example + * 1 - res = Rx.Observable.onErrorResumeNext(xs, ys, zs); + * 1 - res = Rx.Observable.onErrorResumeNext([xs, ys, zs]); + * @returns {Observable} An observable sequence that concatenates the source sequences, even if a sequence terminates exceptionally. + */ + var onErrorResumeNext = Observable.onErrorResumeNext = function () { + var sources = argsOrArray(arguments, 0); + return new AnonymousObservable(function (observer) { + var pos = 0, subscription = new SerialDisposable(), + cancelable = immediateScheduler.scheduleRecursive(function (self) { + var current, d; + if (pos < sources.length) { + current = sources[pos++]; + isPromise(current) && (current = observableFromPromise(current)); + d = new SingleAssignmentDisposable(); + subscription.setDisposable(d); + d.setDisposable(current.subscribe(observer.onNext.bind(observer), function () { + self(); + }, function () { + self(); + })); + } else { + observer.onCompleted(); + } + }); + return new CompositeDisposable(subscription, cancelable); + }); + }; + + /** + * Returns the values from the source observable sequence only after the other observable sequence produces a value. + * @param {Observable | Promise} other The observable sequence or Promise that triggers propagation of elements of the source sequence. + * @returns {Observable} An observable sequence containing the elements of the source sequence starting from the point the other sequence triggered propagation. + */ + observableProto.skipUntil = function (other) { + var source = this; + return new AnonymousObservable(function (observer) { + var isOpen = false; + var disposables = new CompositeDisposable(source.subscribe(function (left) { + isOpen && observer.onNext(left); + }, observer.onError.bind(observer), function () { + isOpen && observer.onCompleted(); + })); + + isPromise(other) && (other = observableFromPromise(other)); + + var rightSubscription = new SingleAssignmentDisposable(); + disposables.add(rightSubscription); + rightSubscription.setDisposable(other.subscribe(function () { + isOpen = true; + rightSubscription.dispose(); + }, observer.onError.bind(observer), function () { + rightSubscription.dispose(); + })); + + return disposables; + }); + }; + + /** + * Transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence. + * @returns {Observable} The observable sequence that at any point in time produces the elements of the most recent inner observable sequence that has been received. + */ + observableProto['switch'] = observableProto.switchLatest = function () { + var sources = this; + return new AnonymousObservable(function (observer) { + var hasLatest = false, + innerSubscription = new SerialDisposable(), + isStopped = false, + latest = 0, + subscription = sources.subscribe(function (innerSource) { + var d = new SingleAssignmentDisposable(), id = ++latest; + hasLatest = true; + innerSubscription.setDisposable(d); + + // Check if Promise or Observable + if (isPromise(innerSource)) { + innerSource = observableFromPromise(innerSource); + } + + d.setDisposable(innerSource.subscribe(function (x) { + if (latest === id) { + observer.onNext(x); + } + }, function (e) { + if (latest === id) { + observer.onError(e); + } + }, function () { + if (latest === id) { + hasLatest = false; + if (isStopped) { + observer.onCompleted(); + } + } + })); + }, observer.onError.bind(observer), function () { + isStopped = true; + if (!hasLatest) { + observer.onCompleted(); + } + }); + return new CompositeDisposable(subscription, innerSubscription); + }); + }; + + /** + * Returns the values from the source observable sequence until the other observable sequence produces a value. + * @param {Observable | Promise} other Observable sequence or Promise that terminates propagation of elements of the source sequence. + * @returns {Observable} An observable sequence containing the elements of the source sequence up to the point the other sequence interrupted further propagation. + */ + observableProto.takeUntil = function (other) { + var source = this; + return new AnonymousObservable(function (observer) { + isPromise(other) && (other = observableFromPromise(other)); + return new CompositeDisposable( + source.subscribe(observer), + other.subscribe(observer.onCompleted.bind(observer), observer.onError.bind(observer), noop) + ); + }); + }; + + function zipArray(second, resultSelector) { + var first = this; + return new AnonymousObservable(function (observer) { + var index = 0, len = second.length; + return first.subscribe(function (left) { + if (index < len) { + var right = second[index++], result; + try { + result = resultSelector(left, right); + } catch (e) { + observer.onError(e); + return; + } + observer.onNext(result); + } else { + observer.onCompleted(); + } + }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); + }); + } + + /** + * Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences or an array have produced an element at a corresponding index. + * The last element in the arguments must be a function to invoke for each series of elements at corresponding indexes in the sources. + * + * @example + * 1 - res = obs1.zip(obs2, fn); + * 1 - res = x1.zip([1,2,3], fn); + * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + observableProto.zip = function () { + if (Array.isArray(arguments[0])) { + return zipArray.apply(this, arguments); + } + var parent = this, sources = slice.call(arguments), resultSelector = sources.pop(); + sources.unshift(parent); + return new AnonymousObservable(function (observer) { + var n = sources.length, + queues = arrayInitialize(n, function () { return []; }), + isDone = arrayInitialize(n, function () { return false; }); + + function next(i) { + var res, queuedValues; + if (queues.every(function (x) { return x.length > 0; })) { + try { + queuedValues = queues.map(function (x) { return x.shift(); }); + res = resultSelector.apply(parent, queuedValues); + } catch (ex) { + observer.onError(ex); + return; + } + observer.onNext(res); + } else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) { + observer.onCompleted(); + } + }; + + function done(i) { + isDone[i] = true; + if (isDone.every(function (x) { return x; })) { + observer.onCompleted(); + } + } + + var subscriptions = new Array(n); + for (var idx = 0; idx < n; idx++) { + (function (i) { + var source = sources[i], sad = new SingleAssignmentDisposable(); + isPromise(source) && (source = observableFromPromise(source)); + sad.setDisposable(source.subscribe(function (x) { + queues[i].push(x); + next(i); + }, observer.onError.bind(observer), function () { + done(i); + })); + subscriptions[i] = sad; + })(idx); + } + + return new CompositeDisposable(subscriptions); + }); + }; + /** + * Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index. + * @param arguments Observable sources. + * @param {Function} resultSelector Function to invoke for each series of elements at corresponding indexes in the sources. + * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + Observable.zip = function () { + var args = slice.call(arguments, 0), + first = args.shift(); + return first.zip.apply(first, args); + }; + + /** + * Merges the specified observable sequences into one observable sequence by emitting a list with the elements of the observable sequences at corresponding indexes. + * @param arguments Observable sources. + * @returns {Observable} An observable sequence containing lists of elements at corresponding indexes. + */ + Observable.zipArray = function () { + var sources = argsOrArray(arguments, 0); + return new AnonymousObservable(function (observer) { + var n = sources.length, + queues = arrayInitialize(n, function () { return []; }), + isDone = arrayInitialize(n, function () { return false; }); + + function next(i) { + if (queues.every(function (x) { return x.length > 0; })) { + var res = queues.map(function (x) { return x.shift(); }); + observer.onNext(res); + } else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) { + observer.onCompleted(); + return; + } + }; + + function done(i) { + isDone[i] = true; + if (isDone.every(identity)) { + observer.onCompleted(); + return; + } + } + + var subscriptions = new Array(n); + for (var idx = 0; idx < n; idx++) { + (function (i) { + subscriptions[i] = new SingleAssignmentDisposable(); + subscriptions[i].setDisposable(sources[i].subscribe(function (x) { + queues[i].push(x); + next(i); + }, observer.onError.bind(observer), function () { + done(i); + })); + })(idx); + } + + var compositeDisposable = new CompositeDisposable(subscriptions); + compositeDisposable.add(disposableCreate(function () { + for (var qIdx = 0, qLen = queues.length; qIdx < qLen; qIdx++) { + queues[qIdx] = []; + } + })); + return compositeDisposable; + }); + }; + + /** + * Hides the identity of an observable sequence. + * @returns {Observable} An observable sequence that hides the identity of the source sequence. + */ + observableProto.asObservable = function () { + var source = this; + return new AnonymousObservable(function (observer) { + return source.subscribe(observer); + }); + }; + + /** + * Projects each element of an observable sequence into zero or more buffers which are produced based on element count information. + * + * @example + * var res = xs.bufferWithCount(10); + * var res = xs.bufferWithCount(10, 1); + * @param {Number} count Length of each buffer. + * @param {Number} [skip] Number of elements to skip between creation of consecutive buffers. If not provided, defaults to the count. + * @returns {Observable} An observable sequence of buffers. + */ + observableProto.bufferWithCount = function (count, skip) { + if (typeof skip !== 'number') { + skip = count; + } + return this.windowWithCount(count, skip).selectMany(function (x) { + return x.toArray(); + }).where(function (x) { + return x.length > 0; + }); + }; + + /** + * Dematerializes the explicit notification values of an observable sequence as implicit notifications. + * @returns {Observable} An observable sequence exhibiting the behavior corresponding to the source sequence's notification values. + */ + observableProto.dematerialize = function () { + var source = this; + return new AnonymousObservable(function (observer) { + return source.subscribe(function (x) { + return x.accept(observer); + }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); + }); + }; + + /** + * Returns an observable sequence that contains only distinct contiguous elements according to the keySelector and the comparer. + * + * var obs = observable.distinctUntilChanged(); + * var obs = observable.distinctUntilChanged(function (x) { return x.id; }); + * var obs = observable.distinctUntilChanged(function (x) { return x.id; }, function (x, y) { return x === y; }); + * + * @param {Function} [keySelector] A function to compute the comparison key for each element. If not provided, it projects the value. + * @param {Function} [comparer] Equality comparer for computed key values. If not provided, defaults to an equality comparer function. + * @returns {Observable} An observable sequence only containing the distinct contiguous elements, based on a computed key value, from the source sequence. + */ + observableProto.distinctUntilChanged = function (keySelector, comparer) { + var source = this; + keySelector || (keySelector = identity); + comparer || (comparer = defaultComparer); + return new AnonymousObservable(function (observer) { + var hasCurrentKey = false, currentKey; + return source.subscribe(function (value) { + var comparerEquals = false, key; + try { + key = keySelector(value); + } catch (exception) { + observer.onError(exception); + return; + } + if (hasCurrentKey) { + try { + comparerEquals = comparer(currentKey, key); + } catch (exception) { + observer.onError(exception); + return; + } + } + if (!hasCurrentKey || !comparerEquals) { + hasCurrentKey = true; + currentKey = key; + observer.onNext(value); + } + }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); + }); + }; + + /** + * Invokes an action for each element in the observable sequence and invokes an action upon graceful or exceptional termination of the observable sequence. + * This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline. + * + * @example + * var res = observable.doAction(observer); + * var res = observable.doAction(onNext); + * var res = observable.doAction(onNext, onError); + * var res = observable.doAction(onNext, onError, onCompleted); + * @param {Mixed} observerOrOnNext Action to invoke for each element in the observable sequence or an observer. + * @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function. + * @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function. + * @returns {Observable} The source sequence with the side-effecting behavior applied. + */ + observableProto['do'] = observableProto.doAction = function (observerOrOnNext, onError, onCompleted) { + var source = this, onNextFunc; + if (typeof observerOrOnNext === 'function') { + onNextFunc = observerOrOnNext; + } else { + onNextFunc = observerOrOnNext.onNext.bind(observerOrOnNext); + onError = observerOrOnNext.onError.bind(observerOrOnNext); + onCompleted = observerOrOnNext.onCompleted.bind(observerOrOnNext); + } + return new AnonymousObservable(function (observer) { + return source.subscribe(function (x) { + try { + onNextFunc(x); + } catch (e) { + observer.onError(e); + } + observer.onNext(x); + }, function (exception) { + if (!onError) { + observer.onError(exception); + } else { + try { + onError(exception); + } catch (e) { + observer.onError(e); + } + observer.onError(exception); + } + }, function () { + if (!onCompleted) { + observer.onCompleted(); + } else { + try { + onCompleted(); + } catch (e) { + observer.onError(e); + } + observer.onCompleted(); + } + }); + }); + }; + + /** + * Invokes a specified action after the source observable sequence terminates gracefully or exceptionally. + * + * @example + * var res = observable.finallyAction(function () { console.log('sequence ended'; }); + * @param {Function} finallyAction Action to invoke after the source observable sequence terminates. + * @returns {Observable} Source sequence with the action-invoking termination behavior applied. + */ + observableProto['finally'] = observableProto.finallyAction = function (action) { + var source = this; + return new AnonymousObservable(function (observer) { + var subscription; + try { + subscription = source.subscribe(observer); + } catch (e) { + action(); + throw e; + } + return disposableCreate(function () { + try { + subscription.dispose(); + } catch (e) { + throw e; + } finally { + action(); + } + }); + }); + }; + + /** + * Ignores all elements in an observable sequence leaving only the termination messages. + * @returns {Observable} An empty observable sequence that signals termination, successful or exceptional, of the source sequence. + */ + observableProto.ignoreElements = function () { + var source = this; + return new AnonymousObservable(function (observer) { + return source.subscribe(noop, observer.onError.bind(observer), observer.onCompleted.bind(observer)); + }); + }; + + /** + * Materializes the implicit notifications of an observable sequence as explicit notification values. + * @returns {Observable} An observable sequence containing the materialized notification values from the source sequence. + */ + observableProto.materialize = function () { + var source = this; + return new AnonymousObservable(function (observer) { + return source.subscribe(function (value) { + observer.onNext(notificationCreateOnNext(value)); + }, function (e) { + observer.onNext(notificationCreateOnError(e)); + observer.onCompleted(); + }, function () { + observer.onNext(notificationCreateOnCompleted()); + observer.onCompleted(); + }); + }); + }; + + /** + * Repeats the observable sequence a specified number of times. If the repeat count is not specified, the sequence repeats indefinitely. + * + * @example + * var res = repeated = source.repeat(); + * var res = repeated = source.repeat(42); + * @param {Number} [repeatCount] Number of times to repeat the sequence. If not provided, repeats the sequence indefinitely. + * @returns {Observable} The observable sequence producing the elements of the given sequence repeatedly. + */ + observableProto.repeat = function (repeatCount) { + return enumerableRepeat(this, repeatCount).concat(); + }; + + /** + * Repeats the source observable sequence the specified number of times or until it successfully terminates. If the retry count is not specified, it retries indefinitely. + * + * @example + * var res = retried = retry.repeat(); + * var res = retried = retry.repeat(42); + * @param {Number} [retryCount] Number of times to retry the sequence. If not provided, retry the sequence indefinitely. + * @returns {Observable} An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully. + */ + observableProto.retry = function (retryCount) { + return enumerableRepeat(this, retryCount).catchException(); + }; + + /** + * Applies an accumulator function over an observable sequence and returns each intermediate result. The optional seed value is used as the initial accumulator value. + * For aggregation behavior with no intermediate results, see Observable.aggregate. + * @example + * var res = source.scan(function (acc, x) { return acc + x; }); + * var res = source.scan(0, function (acc, x) { return acc + x; }); + * @param {Mixed} [seed] The initial accumulator value. + * @param {Function} accumulator An accumulator function to be invoked on each element. + * @returns {Observable} An observable sequence containing the accumulated values. + */ + observableProto.scan = function () { + var hasSeed = false, seed, accumulator, source = this; + if (arguments.length === 2) { + hasSeed = true; + seed = arguments[0]; + accumulator = arguments[1]; + } else { + accumulator = arguments[0]; + } + return new AnonymousObservable(function (observer) { + var hasAccumulation, accumulation, hasValue; + return source.subscribe ( + function (x) { + try { + if (!hasValue) { + hasValue = true; + } + + if (hasAccumulation) { + accumulation = accumulator(accumulation, x); + } else { + accumulation = hasSeed ? accumulator(seed, x) : x; + hasAccumulation = true; + } + } catch (e) { + observer.onError(e); + return; + } + + observer.onNext(accumulation); + }, + observer.onError.bind(observer), + function () { + if (!hasValue && hasSeed) { + observer.onNext(seed); + } + observer.onCompleted(); + } + ); + }); + }; + + /** + * Bypasses a specified number of elements at the end of an observable sequence. + * @description + * This operator accumulates a queue with a length enough to store the first `count` elements. As more elements are + * received, elements are taken from the front of the queue and produced on the result sequence. This causes elements to be delayed. + * @param count Number of elements to bypass at the end of the source sequence. + * @returns {Observable} An observable sequence containing the source sequence elements except for the bypassed ones at the end. + */ + observableProto.skipLast = function (count) { + var source = this; + return new AnonymousObservable(function (observer) { + var q = []; + return source.subscribe(function (x) { + q.push(x); + if (q.length > count) { + observer.onNext(q.shift()); + } + }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); + }); + }; + + /** + * Prepends a sequence of values to an observable sequence with an optional scheduler and an argument list of values to prepend. + * + * var res = source.startWith(1, 2, 3); + * var res = source.startWith(Rx.Scheduler.timeout, 1, 2, 3); + * + * @memberOf Observable# + * @returns {Observable} The source sequence prepended with the specified values. + */ + observableProto.startWith = function () { + var values, scheduler, start = 0; + if (!!arguments.length && 'now' in Object(arguments[0])) { + scheduler = arguments[0]; + start = 1; + } else { + scheduler = immediateScheduler; + } + values = slice.call(arguments, start); + return enumerableFor([observableFromArray(values, scheduler), this]).concat(); + }; + + /** + * Returns a specified number of contiguous elements from the end of an observable sequence, using an optional scheduler to drain the queue. + * + * @example + * var res = source.takeLast(5); + * var res = source.takeLast(5, Rx.Scheduler.timeout); + * + * @description + * This operator accumulates a buffer with a length enough to store elements count elements. Upon completion of + * the source sequence, this buffer is drained on the result sequence. This causes the elements to be delayed. + * @param {Number} count Number of elements to take from the end of the source sequence. + * @param {Scheduler} [scheduler] Scheduler used to drain the queue upon completion of the source sequence. + * @returns {Observable} An observable sequence containing the specified number of elements from the end of the source sequence. + */ + observableProto.takeLast = function (count, scheduler) { + return this.takeLastBuffer(count).selectMany(function (xs) { return observableFromArray(xs, scheduler); }); + }; + + /** + * Returns an array with the specified number of contiguous elements from the end of an observable sequence. + * + * @description + * This operator accumulates a buffer with a length enough to store count elements. Upon completion of the + * source sequence, this buffer is produced on the result sequence. + * @param {Number} count Number of elements to take from the end of the source sequence. + * @returns {Observable} An observable sequence containing a single array with the specified number of elements from the end of the source sequence. + */ + observableProto.takeLastBuffer = function (count) { + var source = this; + return new AnonymousObservable(function (observer) { + var q = []; + return source.subscribe(function (x) { + q.push(x); + if (q.length > count) { + q.shift(); + } + }, observer.onError.bind(observer), function () { + observer.onNext(q); + observer.onCompleted(); + }); + }); + }; + + /** + * Projects each element of an observable sequence into zero or more windows which are produced based on element count information. + * + * var res = xs.windowWithCount(10); + * var res = xs.windowWithCount(10, 1); + * @param {Number} count Length of each window. + * @param {Number} [skip] Number of elements to skip between creation of consecutive windows. If not specified, defaults to the count. + * @returns {Observable} An observable sequence of windows. + */ + observableProto.windowWithCount = function (count, skip) { + var source = this; + if (count <= 0) { + throw new Error(argumentOutOfRange); + } + if (arguments.length === 1) { + skip = count; + } + if (skip <= 0) { + throw new Error(argumentOutOfRange); + } + return new AnonymousObservable(function (observer) { + var m = new SingleAssignmentDisposable(), + refCountDisposable = new RefCountDisposable(m), + n = 0, + q = [], + createWindow = function () { + var s = new Subject(); + q.push(s); + observer.onNext(addRef(s, refCountDisposable)); + }; + createWindow(); + m.setDisposable(source.subscribe(function (x) { + var s; + for (var i = 0, len = q.length; i < len; i++) { + q[i].onNext(x); + } + var c = n - count + 1; + if (c >= 0 && c % skip === 0) { + s = q.shift(); + s.onCompleted(); + } + n++; + if (n % skip === 0) { + createWindow(); + } + }, function (exception) { + while (q.length > 0) { + q.shift().onError(exception); + } + observer.onError(exception); + }, function () { + while (q.length > 0) { + q.shift().onCompleted(); + } + observer.onCompleted(); + })); + return refCountDisposable; + }); + }; + + function concatMap(selector) { + return this.map(function (x, i) { + var result = selector(x, i); + return isPromise(result) ? observableFromPromise(result) : result; + }).concatAll(); + } + + function concatMapObserver(onNext, onError, onCompleted) { + var source = this; + return new AnonymousObservable(function (observer) { + var index = 0; + + return source.subscribe( + function (x) { + observer.onNext(onNext(x, index++)); + }, + function (err) { + observer.onNext(onError(err)); + observer.completed(); + }, + function () { + observer.onNext(onCompleted()); + observer.onCompleted(); + }); + }).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.selectMany(function (x) { return Rx.Observable.range(0, x); }); + * Or: + * Projects each element of an observable sequence to an observable sequence, invokes the result selector for the source element and each of the corresponding inner sequence's elements, and merges the results into one observable sequence. + * + * var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); }, function (x, y) { return x + y; }); + * Or: + * Projects each element of the source observable sequence to the other observable sequence and merges the resulting observable sequences into one observable sequence. + * + * var res = source.selectMany(Rx.Observable.fromArray([1,2,3])); + * @param selector A transform function to apply to each element or an observable sequence to project each element from the + * source sequence onto which could be either an observable or Promise. + * @param {Function} [resultSelector] A transform function to apply to each element of the intermediate sequence. + * @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) { + if (resultSelector) { + return this.concatMap(function (x, i) { + var selectorResult = selector(x, i), + result = isPromise(selectorResult) ? observableFromPromise(selectorResult) : selectorResult; + + return result.map(function (y) { + return resultSelector(x, y, i); + }); + }); + } + if (typeof selector === 'function') { + return concatMap.call(this, selector); + } + return concatMap.call(this, function () { + return selector; + }); + }; + + /** + * Returns the elements of the specified sequence or the specified value in a singleton sequence if the sequence is empty. + * + * var res = obs = xs.defaultIfEmpty(); + * 2 - obs = xs.defaultIfEmpty(false); + * + * @memberOf Observable# + * @param defaultValue The value to return if the sequence is empty. If not provided, this defaults to null. + * @returns {Observable} An observable sequence that contains the specified default value if the source is empty; otherwise, the elements of the source itself. + */ + observableProto.defaultIfEmpty = function (defaultValue) { + var source = this; + if (defaultValue === undefined) { + defaultValue = null; + } + return new AnonymousObservable(function (observer) { + var found = false; + return source.subscribe(function (x) { + found = true; + observer.onNext(x); + }, observer.onError.bind(observer), function () { + if (!found) { + observer.onNext(defaultValue); + } + observer.onCompleted(); + }); + }); + }; + + /** + * Returns an observable sequence that contains only distinct elements according to the keySelector and the comparer. + * Usage of this operator should be considered carefully due to the maintenance of an internal lookup structure which can grow large. + * + * @example + * var res = obs = xs.distinct(); + * 2 - obs = xs.distinct(function (x) { return x.id; }); + * 2 - obs = xs.distinct(function (x) { return x.id; }, function (x) { return x.toString(); }); + * @param {Function} [keySelector] A function to compute the comparison key for each element. + * @param {Function} [keySerializer] Used to serialize the given object into a string for object comparison. + * @returns {Observable} An observable sequence only containing the distinct elements, based on a computed key value, from the source sequence. + */ + observableProto.distinct = function (keySelector, keySerializer) { + var source = this; + keySelector || (keySelector = identity); + keySerializer || (keySerializer = defaultKeySerializer); + return new AnonymousObservable(function (observer) { + var hashSet = {}; + return source.subscribe(function (x) { + var key, serializedKey, otherKey, hasMatch = false; + try { + key = keySelector(x); + serializedKey = keySerializer(key); + } catch (exception) { + observer.onError(exception); + return; + } + for (otherKey in hashSet) { + if (serializedKey === otherKey) { + hasMatch = true; + break; + } + } + if (!hasMatch) { + hashSet[serializedKey] = null; + observer.onNext(x); + } + }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); + }); + }; + + /** + * Groups the elements of an observable sequence according to a specified key selector function and comparer and selects the resulting elements by using a specified function. + * + * @example + * var res = observable.groupBy(function (x) { return x.id; }); + * 2 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }); + * 3 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }, function (x) { return x.toString(); }); + * @param {Function} keySelector A function to extract the key for each element. + * @param {Function} [elementSelector] A function to map each source element to an element in an observable group. + * @param {Function} [keySerializer] Used to serialize the given object into a string for object comparison. + * @returns {Observable} A sequence of observable groups, each of which corresponds to a unique key value, containing all elements that share that same key value. + */ + observableProto.groupBy = function (keySelector, elementSelector, keySerializer) { + return this.groupByUntil(keySelector, elementSelector, function () { + return observableNever(); + }, keySerializer); + }; + + /** + * Groups the elements of an observable sequence according to a specified key selector function. + * A duration selector function is used to control the lifetime of groups. When a group expires, it receives an OnCompleted notification. When a new element with the same + * key value as a reclaimed group occurs, the group will be reborn with a new lifetime request. + * + * @example + * var res = observable.groupByUntil(function (x) { return x.id; }, null, function () { return Rx.Observable.never(); }); + * 2 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }, function () { return Rx.Observable.never(); }); + * 3 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }, function () { return Rx.Observable.never(); }, function (x) { return x.toString(); }); + * @param {Function} keySelector A function to extract the key for each element. + * @param {Function} durationSelector A function to signal the expiration of a group. + * @param {Function} [keySerializer] Used to serialize the given object into a string for object comparison. + * @returns {Observable} + * A sequence of observable groups, each of which corresponds to a unique key value, containing all elements that share that same key value. + * If a group's lifetime expires, a new group with the same key value can be created once an element with such a key value is encoutered. + * + */ + observableProto.groupByUntil = function (keySelector, elementSelector, durationSelector, keySerializer) { + var source = this; + elementSelector || (elementSelector = identity); + keySerializer || (keySerializer = defaultKeySerializer); + return new AnonymousObservable(function (observer) { + var map = {}, + groupDisposable = new CompositeDisposable(), + refCountDisposable = new RefCountDisposable(groupDisposable); + groupDisposable.add(source.subscribe(function (x) { + var duration, durationGroup, element, fireNewMapEntry, group, key, serializedKey, md, writer, w; + try { + key = keySelector(x); + serializedKey = keySerializer(key); + } catch (e) { + for (w in map) { + map[w].onError(e); + } + observer.onError(e); + return; + } + fireNewMapEntry = false; + try { + writer = map[serializedKey]; + if (!writer) { + writer = new Subject(); + map[serializedKey] = writer; + fireNewMapEntry = true; + } + } catch (e) { + for (w in map) { + map[w].onError(e); + } + observer.onError(e); + return; + } + if (fireNewMapEntry) { + group = new GroupedObservable(key, writer, refCountDisposable); + durationGroup = new GroupedObservable(key, writer); + try { + duration = durationSelector(durationGroup); + } catch (e) { + for (w in map) { + map[w].onError(e); + } + observer.onError(e); + return; + } + observer.onNext(group); + md = new SingleAssignmentDisposable(); + groupDisposable.add(md); + var expire = function () { + if (serializedKey in map) { + delete map[serializedKey]; + writer.onCompleted(); + } + groupDisposable.remove(md); + }; + md.setDisposable(duration.take(1).subscribe(noop, function (exn) { + for (w in map) { + map[w].onError(exn); + } + observer.onError(exn); + }, function () { + expire(); + })); + } + try { + element = elementSelector(x); + } catch (e) { + for (w in map) { + map[w].onError(e); + } + observer.onError(e); + return; + } + writer.onNext(element); + }, function (ex) { + for (var w in map) { + map[w].onError(ex); + } + observer.onError(ex); + }, function () { + for (var w in map) { + map[w].onCompleted(); + } + observer.onCompleted(); + })); + return refCountDisposable; + }); + }; + + /** + * Projects each element of an observable sequence into a new form by incorporating the element's index. + * @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element. + * @param {Any} [thisArg] Object to use as this when executing callback. + * @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source. + */ + observableProto.select = observableProto.map = function (selector, thisArg) { + var parent = this; + return new AnonymousObservable(function (observer) { + var count = 0; + return parent.subscribe(function (value) { + var result; + try { + result = selector.call(thisArg, value, count++, parent); + } catch (exception) { + observer.onError(exception); + return; + } + observer.onNext(result); + }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); + }); + }; + + /** + * Retrieves the value of a specified property from all elements in the Observable sequence. + * @param {String} property The property to pluck. + * @returns {Observable} Returns a new Observable sequence of property values. + */ + observableProto.pluck = function (property) { + return this.select(function (x) { return x[property]; }); + }; + + function selectMany(selector) { + return this.select(function (x, i) { + var result = selector(x, i); + return isPromise(result) ? observableFromPromise(result) : result; + }).mergeObservable(); + } + + function selectManyObserver(onNext, onError, onCompleted) { + var source = this; + return new AnonymousObservable(function (observer) { + var index = 0; + + return source.subscribe( + function (x) { + observer.onNext(onNext(x, index++)); + }, + function (err) { + observer.onNext(onError(err)); + observer.completed(); + }, + function () { + observer.onNext(onCompleted()); + observer.onCompleted(); + }); + }).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 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.selectMany = observableProto.flatMap = function (selector, resultSelector) { + if (resultSelector) { + return this.selectMany(function (x, i) { + var selectorResult = selector(x, i), + result = isPromise(selectorResult) ? observableFromPromise(selectorResult) : selectorResult; + + return result.select(function (y) { + return resultSelector(x, y, i); + }); + }); + } + if (typeof selector === 'function') { + return selectMany.call(this, selector); + } + return selectMany.call(this, function () { + return selector; + }); + }; + + /** + * Projects each element of an observable sequence into a new sequence of observable sequences by incorporating the element's index and then + * transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence. + * @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element. + * @param {Any} [thisArg] Object to use as this when executing callback. + * @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source producing an Observable of Observable sequences + * and that at any point in time produces the elements of the most recent inner observable sequence that has been received. + */ + observableProto.selectSwitch = observableProto.flatMapLatest = observableProto.switchMap = function (selector, thisArg) { + return this.select(selector, thisArg).switchLatest(); + }; + + /** + * Bypasses a specified number of elements in an observable sequence and then returns the remaining elements. + * @param {Number} count The number of elements to skip before returning the remaining elements. + * @returns {Observable} An observable sequence that contains the elements that occur after the specified index in the input sequence. + */ + observableProto.skip = function (count) { + if (count < 0) { + throw new Error(argumentOutOfRange); + } + var observable = this; + return new AnonymousObservable(function (observer) { + var remaining = count; + return observable.subscribe(function (x) { + if (remaining <= 0) { + observer.onNext(x); + } else { + remaining--; + } + }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); + }); + }; + + /** + * Bypasses elements in an observable sequence as long as a specified condition is true and then returns the remaining elements. + * The element's index is used in the logic of the predicate function. + * + * var res = source.skipWhile(function (value) { return value < 10; }); + * var res = source.skipWhile(function (value, index) { return value < 10 || index < 10; }); + * @param {Function} predicate A function to test each element for a condition; the second parameter of the function represents the index of the source element. + * @param {Any} [thisArg] Object to use as this when executing callback. + * @returns {Observable} An observable sequence that contains the elements from the input sequence starting at the first element in the linear series that does not pass the test specified by predicate. + */ + observableProto.skipWhile = function (predicate, thisArg) { + var source = this; + return new AnonymousObservable(function (observer) { + var i = 0, running = false; + return source.subscribe(function (x) { + if (!running) { + try { + running = !predicate.call(thisArg, x, i++, source); + } catch (e) { + observer.onError(e); + return; + } + } + if (running) { + observer.onNext(x); + } + }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); + }); + }; + + /** + * Returns a specified number of contiguous elements from the start of an observable sequence, using the specified scheduler for the edge case of take(0). + * + * var res = source.take(5); + * var res = source.take(0, Rx.Scheduler.timeout); + * @param {Number} count The number of elements to return. + * @param {Scheduler} [scheduler] Scheduler used to produce an OnCompleted message in case 0; + }, + /** + * Notifies all subscribed observers about the end of the sequence. + */ + onCompleted: function () { + checkDisposed.call(this); + if (!this.isStopped) { + var os = this.observers.slice(0); + this.isStopped = true; + for (var i = 0, len = os.length; i < len; i++) { + os[i].onCompleted(); + } + + this.observers = []; + } + }, + /** + * Notifies all subscribed observers about the exception. + * @param {Mixed} error The exception to send to all observers. + */ + onError: function (error) { + checkDisposed.call(this); + if (!this.isStopped) { + var os = this.observers.slice(0); + this.isStopped = true; + this.exception = error; + + for (var i = 0, len = os.length; i < len; i++) { + os[i].onError(error); + } + + this.observers = []; + } + }, + /** + * Notifies all subscribed observers about the arrival of the specified element in the sequence. + * @param {Mixed} value The value to send to all observers. + */ + onNext: function (value) { + checkDisposed.call(this); + if (!this.isStopped) { + this.value = value; + var os = this.observers.slice(0); + for (var i = 0, len = os.length; i < len; i++) { + os[i].onNext(value); + } + } + }, + /** + * Unsubscribe all observers and release resources. + */ + dispose: function () { + this.isDisposed = true; + this.observers = null; + this.value = null; + this.exception = null; + } + }); + + return BehaviorSubject; + }(Observable)); + + /** + * Represents an object that is both an observable sequence as well as an observer. + * Each notification is broadcasted to all subscribed and future observers, subject to buffer trimming policies. + */ + var ReplaySubject = Rx.ReplaySubject = (function (_super) { + + function RemovableDisposable (subject, observer) { + this.subject = subject; + this.observer = observer; + }; + + RemovableDisposable.prototype.dispose = function () { + this.observer.dispose(); + if (!this.subject.isDisposed) { + var idx = this.subject.observers.indexOf(this.observer); + this.subject.observers.splice(idx, 1); + } + }; + + function subscribe(observer) { + var so = new ScheduledObserver(this.scheduler, observer), + subscription = new RemovableDisposable(this, so); + checkDisposed.call(this); + this._trim(this.scheduler.now()); + this.observers.push(so); + + var n = this.q.length; + + for (var i = 0, len = this.q.length; i < len; i++) { + so.onNext(this.q[i].value); + } + + if (this.hasError) { + n++; + so.onError(this.error); + } else if (this.isStopped) { + n++; + so.onCompleted(); + } + + so.ensureActive(n); + return subscription; + } + + inherits(ReplaySubject, _super); + + /** + * Initializes a new instance of the ReplaySubject class with the specified buffer size, window size and scheduler. + * @param {Number} [bufferSize] Maximum element count of the replay buffer. + * @param {Number} [windowSize] Maximum time length of the replay buffer. + * @param {Scheduler} [scheduler] Scheduler the observers are invoked on. + */ + function ReplaySubject(bufferSize, windowSize, scheduler) { + this.bufferSize = bufferSize == null ? Number.MAX_VALUE : bufferSize; + this.windowSize = windowSize == null ? Number.MAX_VALUE : windowSize; + this.scheduler = scheduler || currentThreadScheduler; + this.q = []; + this.observers = []; + this.isStopped = false; + this.isDisposed = false; + this.hasError = false; + this.error = null; + _super.call(this, subscribe); + } + + addProperties(ReplaySubject.prototype, Observer, { + /** + * Indicates whether the subject has observers subscribed to it. + * @returns {Boolean} Indicates whether the subject has observers subscribed to it. + */ + hasObservers: function () { + return this.observers.length > 0; + }, + /* @private */ + _trim: function (now) { + while (this.q.length > this.bufferSize) { + this.q.shift(); + } + while (this.q.length > 0 && (now - this.q[0].interval) > this.windowSize) { + this.q.shift(); + } + }, + /** + * Notifies all subscribed observers about the arrival of the specified element in the sequence. + * @param {Mixed} value The value to send to all observers. + */ + onNext: function (value) { + var observer; + checkDisposed.call(this); + if (!this.isStopped) { + var now = this.scheduler.now(); + this.q.push({ interval: now, value: value }); + this._trim(now); + + var o = this.observers.slice(0); + for (var i = 0, len = o.length; i < len; i++) { + observer = o[i]; + observer.onNext(value); + observer.ensureActive(); + } + } + }, + /** + * Notifies all subscribed observers about the exception. + * @param {Mixed} error The exception to send to all observers. + */ + onError: function (error) { + var observer; + checkDisposed.call(this); + if (!this.isStopped) { + this.isStopped = true; + this.error = error; + this.hasError = true; + var now = this.scheduler.now(); + this._trim(now); + var o = this.observers.slice(0); + for (var i = 0, len = o.length; i < len; i++) { + observer = o[i]; + observer.onError(error); + observer.ensureActive(); + } + this.observers = []; + } + }, + /** + * Notifies all subscribed observers about the end of the sequence. + */ + onCompleted: function () { + var observer; + checkDisposed.call(this); + if (!this.isStopped) { + this.isStopped = true; + var now = this.scheduler.now(); + this._trim(now); + var o = this.observers.slice(0); + for (var i = 0, len = o.length; i < len; i++) { + observer = o[i]; + observer.onCompleted(); + observer.ensureActive(); + } + this.observers = []; + } + }, + /** + * Unsubscribe all observers and release resources. + */ + dispose: function () { + this.isDisposed = true; + this.observers = null; + } + }); + + return ReplaySubject; + }(Observable)); + + /** @private */ + var ConnectableObservable = Rx.ConnectableObservable = (function (_super) { + inherits(ConnectableObservable, _super); + + /** + * @constructor + * @private + */ + function ConnectableObservable(source, subject) { + var state = { + subject: subject, + source: source.asObservable(), + hasSubscription: false, + subscription: null + }; + + this.connect = function () { + if (!state.hasSubscription) { + state.hasSubscription = true; + state.subscription = new CompositeDisposable(state.source.subscribe(state.subject), disposableCreate(function () { + state.hasSubscription = false; + })); + } + return state.subscription; + }; + + function subscribe(observer) { + return state.subject.subscribe(observer); + } + + _super.call(this, subscribe); + } + + /** + * @private + * @memberOf ConnectableObservable + */ + ConnectableObservable.prototype.connect = function () { return this.connect(); }; + + /** + * @private + * @memberOf ConnectableObservable + */ + ConnectableObservable.prototype.refCount = function () { + var connectableSubscription = null, count = 0, source = this; + return new AnonymousObservable(function (observer) { + var shouldConnect, subscription; + count++; + shouldConnect = count === 1; + subscription = source.subscribe(observer); + if (shouldConnect) { + connectableSubscription = source.connect(); + } + return disposableCreate(function () { + subscription.dispose(); + count--; + if (count === 0) { + connectableSubscription.dispose(); + } + }); + }); + }; + + return ConnectableObservable; + }(Observable)); + + // Real Dictionary + 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]; + var noSuchkey = "no such key"; + var 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 obj.getTime(); + } + + if (obj.getHashCode) { + return obj.getHashCode(); + } + + var id = 17 * uniqueIdCounter++; + obj.getHashCode = function () { return id; }; + return id; + }; + } ()); + + function newEntry() { + return { key: null, value: null, next: 0, hashCode: 0 }; + } + + // Dictionary implementation + + var Dictionary = function (capacity, comparer) { + if (capacity < 0) { + throw new Error('out of range') + } + if (capacity > 0) { + this._initialize(capacity); + } + + this.comparer = comparer || defaultComparer; + this.freeCount = 0; + this.size = 0; + this.freeList = -1; + }; + + Dictionary.prototype._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; + }; + Dictionary.prototype.count = function () { + return this.size; + }; + Dictionary.prototype.add = function (key, value) { + return this._insert(key, value, true); + }; + Dictionary.prototype._insert = function (key, value, add) { + if (!this.buckets) { + this._initialize(0); + } + var index3; + var num = getHashCode(key) & 2147483647; + var 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; + }; + + Dictionary.prototype._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; + }; + + Dictionary.prototype.remove = function (key) { + if (this.buckets) { + var num = getHashCode(key) & 2147483647; + var index1 = num % this.buckets.length; + var 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; + }; + + Dictionary.prototype.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; + }; + + Dictionary.prototype._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; + }; + + Dictionary.prototype.count = function () { + return this.size - this.freeCount; + }; + + Dictionary.prototype.tryGetValue = function (key) { + var entry = this._findEntry(key); + if (entry >= 0) { + return this.entries[entry].value; + } + return undefined; + }; + + Dictionary.prototype.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; + }; + + Dictionary.prototype.get = function (key) { + var entry = this._findEntry(key); + if (entry >= 0) { + return this.entries[entry].value; + } + throw new Error(noSuchkey); + }; + + Dictionary.prototype.set = function (key, value) { + this._insert(key, value, false); + }; + + Dictionary.prototype.containskey = function (key) { + return this._findEntry(key) >= 0; + }; + + /** + * 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(), + leftDone = false, + leftId = 0, + leftMap = new Dictionary(), + rightDone = false, + rightId = 0, + rightMap = new Dictionary(); + group.add(left.subscribe(function (value) { + var duration, + expire, + id = leftId++, + md = new SingleAssignmentDisposable(), + result, + values; + leftMap.add(id, value); + group.add(md); + expire = function () { + if (leftMap.remove(id) && leftMap.count() === 0 && leftDone) { + observer.onCompleted(); + } + return group.remove(md); + }; + try { + duration = leftDurationSelector(value); + } catch (e) { + observer.onError(e); + return; + } + md.setDisposable(duration.take(1).subscribe(noop, observer.onError.bind(observer), function () { expire(); })); + values = rightMap.getValues(); + for (var i = 0; i < values.length; i++) { + try { + result = resultSelector(value, values[i]); + } catch (exception) { + observer.onError(exception); + return; + } + observer.onNext(result); + } + }, observer.onError.bind(observer), function () { + leftDone = true; + if (rightDone || leftMap.count() === 0) { + observer.onCompleted(); + } + })); + group.add(right.subscribe(function (value) { + var duration, + expire, + id = rightId++, + md = new SingleAssignmentDisposable(), + result, + values; + rightMap.add(id, value); + group.add(md); + expire = function () { + if (rightMap.remove(id) && rightMap.count() === 0 && rightDone) { + observer.onCompleted(); + } + return group.remove(md); + }; + try { + duration = rightDurationSelector(value); + } catch (exception) { + observer.onError(exception); + return; + } + md.setDisposable(duration.take(1).subscribe(noop, observer.onError.bind(observer), function () { expire(); })); + values = leftMap.getValues(); + for (var i = 0; i < values.length; i++) { + try { + result = resultSelector(values[i], value); + } catch (exception) { + observer.onError(exception); + return; + } + observer.onNext(result); + } + }, observer.onError.bind(observer), function () { + rightDone = true; + if (leftDone || rightMap.count() === 0) { + observer.onCompleted(); + } + })); + return group; + }); + }; + + /** + * Correlates the elements of two sequences based on overlapping durations, and groups the results. + * + * @param {Observable} right The right observable sequence to join elements for. + * @param {Function} leftDurationSelector A function to select the duration (expressed as an observable sequence) of each element of the left observable sequence, used to determine overlap. + * @param {Function} rightDurationSelector A function to select the duration (expressed as an observable sequence) of each element of the right observable sequence, used to determine overlap. + * @param {Function} resultSelector A function invoked to compute a result element for any element of the left sequence with overlapping elements from the right observable sequence. The first parameter passed to the function is an element of the left sequence. The second parameter passed to the function is an observable sequence with elements from the right sequence that overlap with the left sequence's element. + * @returns {Observable} An observable sequence that contains result elements computed from source elements that have an overlapping duration. + */ + observableProto.groupJoin = function (right, leftDurationSelector, rightDurationSelector, resultSelector) { + var left = this; + return new AnonymousObservable(function (observer) { + var nothing = function () {}; + var group = new CompositeDisposable(); + var r = new RefCountDisposable(group); + var leftMap = new Dictionary(); + var rightMap = new Dictionary(); + var leftID = 0; + var rightID = 0; + + group.add(left.subscribe( + function (value) { + var s = new Subject(); + var id = leftID++; + leftMap.add(id, s); + var i, len, leftValues, rightValues; + + var result; + try { + result = resultSelector(value, addRef(s, r)); + } catch (e) { + leftValues = leftMap.getValues(); + for (i = 0, len = leftValues.length; i < len; i++) { + leftValues[i].onError(e); + } + observer.onError(e); + return; + } + observer.onNext(result); + + rightValues = rightMap.getValues(); + for (i = 0, len = rightValues.length; i < len; i++) { + s.onNext(rightValues[i]); + } + + var md = new SingleAssignmentDisposable(); + group.add(md); + + var expire = function () { + if (leftMap.remove(id)) { + s.onCompleted(); + } + + group.remove(md); + }; + + var duration; + try { + duration = leftDurationSelector(value); + } catch (e) { + leftValues = leftMap.getValues(); + for (i = 0, len = leftMap.length; i < len; i++) { + leftValues[i].onError(e); + } + observer.onError(e); + return; + } + + md.setDisposable(duration.take(1).subscribe( + nothing, + function (e) { + leftValues = leftMap.getValues(); + for (i = 0, len = leftValues.length; i < len; i++) { + leftValues[i].onError(e); + } + observer.onError(e); + }, + expire) + ); + }, + function (e) { + var leftValues = leftMap.getValues(); + for (var i = 0, len = leftValues.length; i < len; i++) { + leftValues[i].onError(e); + } + observer.onError(e); + }, + observer.onCompleted.bind(observer))); + + group.add(right.subscribe( + function (value) { + var leftValues, i, len; + 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) { + leftValues = leftMap.getValues(); + for (i = 0, len = leftMap.length; i < len; i++) { + leftValues[i].onError(e); + } + observer.onError(e); + return; + } + md.setDisposable(duration.take(1).subscribe( + nothing, + function (e) { + leftValues = leftMap.getValues(); + for (i = 0, len = leftMap.length; i < len; i++) { + leftValues[i].onError(e); + } + observer.onError(e); + }, + expire) + ); + + leftValues = leftMap.getValues(); + for (i = 0, len = leftValues.length; i < len; i++) { + leftValues[i].onNext(value); + } + }, + function (e) { + var leftValues = leftMap.getValues(); + for (var i = 0, len = leftValues.length; i < len; i++) { + leftValues[i].onError(e); + } + observer.onError(e); + })); + + return r; + }); + }; + + /** + * Projects each element of an observable sequence into zero or more buffers. + * + * @param {Mixed} bufferOpeningsOrClosingSelector Observable sequence whose elements denote the creation of new windows, or, a function invoked to define the boundaries of the produced windows (a new window is started when the previous one is closed, resulting in non-overlapping windows). + * @param {Function} [bufferClosingSelector] A function invoked to define the closing of each produced window. If a closing selector function is specified for the first parameter, this parameter is ignored. + * @returns {Observable} An observable sequence of windows. + */ + observableProto.buffer = function (bufferOpeningsOrClosingSelector, bufferClosingSelector) { + return this.window.apply(this, arguments).selectMany(function (x) { return x.toArray(); }); + }; + + /** + * Projects each element of an observable sequence into zero or more windows. + * + * @param {Mixed} windowOpeningsOrClosingSelector Observable sequence whose elements denote the creation of new windows, or, a function invoked to define the boundaries of the produced windows (a new window is started when the previous one is closed, resulting in non-overlapping windows). + * @param {Function} [windowClosingSelector] A function invoked to define the closing of each produced window. If a closing selector function is specified for the first parameter, this parameter is ignored. + * @returns {Observable} An observable sequence of windows. + */ + observableProto.window = function (windowOpeningsOrClosingSelector, windowClosingSelector) { + if (arguments.length === 1 && typeof arguments[0] !== 'function') { + return observableWindowWithBounaries.call(this, windowOpeningsOrClosingSelector); + } + return typeof windowOpeningsOrClosingSelector === 'function' ? + observableWindowWithClosingSelector.call(this, windowOpeningsOrClosingSelector) : + observableWindowWithOpenings.call(this, windowOpeningsOrClosingSelector, windowClosingSelector); + }; + + function observableWindowWithOpenings(windowOpenings, windowClosingSelector) { + return windowOpenings.groupJoin(this, windowClosingSelector, function () { + return observableEmpty(); + }, function (_, window) { + return window; + }); + } + + function observableWindowWithBounaries(windowBoundaries) { + var source = this; + return new AnonymousObservable(function (observer) { + var window = new Subject(), + d = new CompositeDisposable(), + r = new RefCountDisposable(d); + + observer.onNext(addRef(window, r)); + + d.add(source.subscribe(function (x) { + window.onNext(x); + }, function (err) { + window.onError(err); + observer.onError(err); + }, function () { + window.onCompleted(); + observer.onCompleted(); + })); + + d.add(windowBoundaries.subscribe(function (w) { + window.onCompleted(); + window = new Subject(); + observer.onNext(addRef(window, r)); + }, function (err) { + window.onError(err); + observer.onError(err); + }, function () { + window.onCompleted(); + observer.onCompleted(); + })); + + return r; + }); + } + + function observableWindowWithClosingSelector(windowClosingSelector) { + var source = this; + return new AnonymousObservable(function (observer) { + var createWindowClose, + m = new SerialDisposable(), + d = new CompositeDisposable(m), + r = new RefCountDisposable(d), + window = new Subject(); + observer.onNext(addRef(window, r)); + d.add(source.subscribe(function (x) { + window.onNext(x); + }, function (ex) { + window.onError(ex); + observer.onError(ex); + }, function () { + window.onCompleted(); + observer.onCompleted(); + })); + createWindowClose = function () { + var m1, windowClose; + try { + windowClose = windowClosingSelector(); + } catch (exception) { + observer.onError(exception); + return; + } + m1 = new SingleAssignmentDisposable(); + m.setDisposable(m1); + m1.setDisposable(windowClose.take(1).subscribe(noop, function (ex) { + window.onError(ex); + observer.onError(ex); + }, function () { + window.onCompleted(); + window = new Subject(); + observer.onNext(addRef(window, r)); + createWindowClose(); + })); + }; + createWindowClose(); + return r; + }); + } + + /** + * Returns a new observable that triggers on the second and subsequent triggerings of the input observable. + * The Nth triggering of the input observable passes the arguments from the N-1th and Nth triggering as a pair. + * The argument passed to the N-1th triggering is held in hidden internal state until the Nth triggering occurs. + * @returns {Observable} An observable that triggers on successive pairs of observations from the input observable as an array. + */ + observableProto.pairwise = function () { + var source = this; + return new AnonymousObservable(function (observer) { + var previous, hasPrevious = false; + return source.subscribe( + function (x) { + if (hasPrevious) { + observer.onNext([previous, x]); + } else { + hasPrevious = true; + } + previous = x; + }, + observer.onError.bind(observer), + observer.onCompleted.bind(observer)); + }); + }; + /** + * Returns two observables which partition the observations of the source by the given function. + * The first will trigger observations for those values for which the predicate returns true. + * The second will trigger observations for those values where the predicate returns false. + * The predicate is executed once for each subscribed observer. + * Both also propagate all error observations arising from the source and each completes + * when the source completes. + * @param {Function} predicate + * The function to determine which output Observable will trigger a particular observation. + * @returns {Array} + * An array of observables. The first triggers when the predicate returns true, + * and the second triggers when the predicate returns false. + */ + observableProto.partition = function(predicate, thisArg) { + var published = this.publish().refCount(); + return [ + published.filter(predicate, thisArg), + published.filter(function (x, i, o) { return !predicate.call(thisArg, x, i, o); }) + ]; + }; + + function enumerableWhile(condition, source) { + return new Enumerable(function () { + return new Enumerator(function () { + return condition() ? + { done: false, value: source } : + { done: true, value: undefined }; + }); + }); + } + + /** + * Returns an observable sequence that is the result of invoking the selector on the source sequence, without sharing subscriptions. + * This operator allows for a fluent style of writing queries that use the same sequence multiple times. + * + * @param {Function} selector Selector function which can use the source sequence as many times as needed, without sharing subscriptions to the source sequence. + * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. + */ + observableProto.letBind = observableProto['let'] = function (func) { + return func(this); + }; + + /** + * Determines whether an observable collection contains values. There is an alias for this method called 'ifThen' for browsers 0) { + isOwner = !isAcquired; + isAcquired = true; + } + if (isOwner) { + m.setDisposable(scheduler.scheduleRecursive(function (self) { + var work; + if (q.length > 0) { + work = q.shift(); + } else { + isAcquired = false; + return; + } + var m1 = new SingleAssignmentDisposable(); + d.add(m1); + m1.setDisposable(work.subscribe(function (x) { + observer.onNext(x); + var result = null; + try { + result = selector(x); + } catch (e) { + observer.onError(e); + } + q.push(result); + activeCount++; + ensureActive(); + }, observer.onError.bind(observer), function () { + d.remove(m1); + activeCount--; + if (activeCount === 0) { + observer.onCompleted(); + } + })); + self(); + })); + } + }; + + q.push(source); + activeCount++; + ensureActive(); + return d; + }); + }; + + /** + * Runs all observable sequences in parallel and collect their last elements. + * + * @example + * 1 - res = Rx.Observable.forkJoin([obs1, obs2]); + * 1 - res = Rx.Observable.forkJoin(obs1, obs2, ...); + * @returns {Observable} An observable sequence with an array collecting the last elements of all the input sequences. + */ + Observable.forkJoin = function () { + var allSources = argsOrArray(arguments, 0); + return new AnonymousObservable(function (subscriber) { + var count = allSources.length; + if (count === 0) { + subscriber.onCompleted(); + return disposableEmpty; + } + var group = new CompositeDisposable(), + finished = false, + hasResults = new Array(count), + hasCompleted = new Array(count), + results = new Array(count); + + for (var idx = 0; idx < count; idx++) { + (function (i) { + var source = allSources[i]; + isPromise(source) && (source = observableFromPromise(source)); + group.add( + source.subscribe( + function (value) { + if (!finished) { + hasResults[i] = true; + results[i] = value; + } + }, + function (e) { + finished = true; + subscriber.onError(e); + group.dispose(); + }, + function () { + if (!finished) { + if (!hasResults[i]) { + subscriber.onCompleted(); + return; + } + hasCompleted[i] = true; + for (var ix = 0; ix < count; ix++) { + if (!hasCompleted[ix]) { return; } + } + finished = true; + subscriber.onNext(results); + subscriber.onCompleted(); + } + })); + })(idx); + } + + return group; + }); + }; + + /** + * Runs two observable sequences in parallel and combines their last elemenets. + * + * @param {Observable} second Second observable sequence. + * @param {Function} resultSelector Result selector function to invoke with the last elements of both sequences. + * @returns {Observable} An observable sequence with the result of calling the selector function with the last elements of both input sequences. + */ + observableProto.forkJoin = function (second, resultSelector) { + var first = this; + + return new AnonymousObservable(function (observer) { + var leftStopped = false, rightStopped = false, + hasLeft = false, hasRight = false, + lastLeft, lastRight, + leftSubscription = new SingleAssignmentDisposable(), rightSubscription = new SingleAssignmentDisposable(); + + isPromise(second) && (second = observableFromPromise(second)); + + leftSubscription.setDisposable( + first.subscribe(function (left) { + hasLeft = true; + lastLeft = left; + }, function (err) { + rightSubscription.dispose(); + observer.onError(err); + }, function () { + leftStopped = true; + if (rightStopped) { + if (!hasLeft) { + observer.onCompleted(); + } else if (!hasRight) { + observer.onCompleted(); + } else { + var result; + try { + result = resultSelector(lastLeft, lastRight); + } catch (e) { + observer.onError(e); + return; + } + observer.onNext(result); + observer.onCompleted(); + } + } + }) + ); + + rightSubscription.setDisposable( + second.subscribe(function (right) { + hasRight = true; + lastRight = right; + }, function (err) { + leftSubscription.dispose(); + observer.onError(err); + }, function () { + rightStopped = true; + if (leftStopped) { + if (!hasLeft) { + observer.onCompleted(); + } else if (!hasRight) { + observer.onCompleted(); + } else { + var result; + try { + result = resultSelector(lastLeft, lastRight); + } catch (e) { + observer.onError(e); + return; + } + observer.onNext(result); + observer.onCompleted(); + } + } + }) + ); + + return new CompositeDisposable(leftSubscription, rightSubscription); + }); + }; + + /** + * Comonadic bind operator. + * @param {Function} selector A transform function to apply to each element. + * @param {Object} scheduler Scheduler used to execute the operation. If not specified, defaults to the ImmediateScheduler. + * @returns {Observable} An observable sequence which results from the comonadic bind operation. + */ + observableProto.manySelect = function (selector, scheduler) { + scheduler || (scheduler = immediateScheduler); + var source = this; + return observableDefer(function () { + var chain; + + return source + .select( + function (x) { + var curr = new ChainObservable(x); + if (chain) { + chain.onNext(x); + } + chain = curr; + + return curr; + }) + .doAction( + noop, + function (e) { + if (chain) { + chain.onError(e); + } + }, + function () { + if (chain) { + chain.onCompleted(); + } + }) + .observeOn(scheduler) + .select(function (x, i, o) { return selector(x, i, o); }); + }); + }; + + var ChainObservable = (function (_super) { + + function subscribe (observer) { + var self = this, g = new CompositeDisposable(); + g.add(currentThreadScheduler.schedule(function () { + observer.onNext(self.head); + g.add(self.tail.mergeObservable().subscribe(observer)); + })); + + return g; + } + + inherits(ChainObservable, _super); + + function ChainObservable(head) { + _super.call(this, subscribe); + this.head = head; + this.tail = new AsyncSubject(); + } + + addProperties(ChainObservable.prototype, Observer, { + onCompleted: function () { + this.onNext(Observable.empty()); + }, + onError: function (e) { + this.onNext(Observable.throwException(e)); + }, + onNext: function (v) { + this.tail.onNext(v); + this.tail.onCompleted(); + } + }); + + return ChainObservable; + + }(Observable)); + + /** @private */ + var Map = (function () { + + /** + * @constructor + * @private + */ + function Map() { + this.keys = []; + this.values = []; + } + + /** + * @private + * @memberOf Map# + */ + Map.prototype['delete'] = function (key) { + var i = this.keys.indexOf(key); + if (i !== -1) { + this.keys.splice(i, 1); + this.values.splice(i, 1); + } + return i !== -1; + }; + + /** + * @private + * @memberOf Map# + */ + Map.prototype.get = function (key, fallback) { + var i = this.keys.indexOf(key); + return i !== -1 ? this.values[i] : fallback; + }; + + /** + * @private + * @memberOf Map# + */ + Map.prototype.set = function (key, value) { + var i = this.keys.indexOf(key); + if (i !== -1) { + this.values[i] = value; + } + this.values[this.keys.push(key) - 1] = value; + }; + + /** + * @private + * @memberOf Map# + */ + Map.prototype.size = function () { return this.keys.length; }; + + /** + * @private + * @memberOf Map# + */ + Map.prototype.has = function (key) { + return this.keys.indexOf(key) !== -1; + }; + + /** + * @private + * @memberOf Map# + */ + Map.prototype.getKeys = function () { return this.keys.slice(0); }; + + /** + * @private + * @memberOf Map# + */ + Map.prototype.getValues = function () { return this.values.slice(0); }; + + return Map; + }()); + + /** + * @constructor + * Represents a join pattern over observable sequences. + */ + function Pattern(patterns) { + this.patterns = patterns; + } + + /** + * Creates a pattern that matches the current plan matches and when the specified observable sequences has an available value. + * + * @param other Observable sequence to match in addition to the current pattern. + * @return Pattern object that matches when all observable sequences in the pattern have an available value. + */ + Pattern.prototype.and = function (other) { + var patterns = this.patterns.slice(0); + patterns.push(other); + return new Pattern(patterns); + }; + + /** + * Matches when all observable sequences in the pattern (specified using a chain of and operators) have an available value and projects the values. + * + * @param selector Selector that will be invoked with available values from the source sequences, in the same order of the sequences in the pattern. + * @return Plan that produces the projected values, to be fed (with other plans) to the when operator. + */ + Pattern.prototype.then = function (selector) { + return new Plan(this, selector); + }; + + function Plan(expression, selector) { + this.expression = expression; + this.selector = selector; + } + + Plan.prototype.activate = function (externalSubscriptions, observer, deactivate) { + var self = this; + var joinObservers = []; + for (var i = 0, len = this.expression.patterns.length; i < len; i++) { + joinObservers.push(planCreateObserver(externalSubscriptions, this.expression.patterns[i], observer.onError.bind(observer))); + } + var activePlan = new ActivePlan(joinObservers, function () { + var result; + try { + result = self.selector.apply(self, arguments); + } catch (exception) { + observer.onError(exception); + return; + } + observer.onNext(result); + }, function () { + for (var j = 0, jlen = joinObservers.length; j < jlen; j++) { + joinObservers[j].removeActivePlan(activePlan); + } + deactivate(activePlan); + }); + for (i = 0, len = joinObservers.length; i < len; i++) { + joinObservers[i].addActivePlan(activePlan); + } + return activePlan; + }; + + function planCreateObserver(externalSubscriptions, observable, onError) { + var entry = externalSubscriptions.get(observable); + if (!entry) { + var observer = new JoinObserver(observable, onError); + externalSubscriptions.set(observable, observer); + return observer; + } + return entry; + } + + // Active Plan + function ActivePlan(joinObserverArray, onNext, onCompleted) { + var i, joinObserver; + this.joinObserverArray = joinObserverArray; + this.onNext = onNext; + this.onCompleted = onCompleted; + this.joinObservers = new Map(); + for (i = 0; i < this.joinObserverArray.length; i++) { + joinObserver = this.joinObserverArray[i]; + this.joinObservers.set(joinObserver, joinObserver); + } + } + + ActivePlan.prototype.dequeue = function () { + var values = this.joinObservers.getValues(); + for (var i = 0, len = values.length; i < len; i++) { + values[i].queue.shift(); + } + }; + ActivePlan.prototype.match = function () { + var firstValues, i, len, isCompleted, values, hasValues = true; + for (i = 0, len = this.joinObserverArray.length; i < len; i++) { + if (this.joinObserverArray[i].queue.length === 0) { + hasValues = false; + break; + } + } + if (hasValues) { + firstValues = []; + isCompleted = false; + for (i = 0, len = this.joinObserverArray.length; i < len; i++) { + firstValues.push(this.joinObserverArray[i].queue[0]); + if (this.joinObserverArray[i].queue[0].kind === 'C') { + isCompleted = true; + } + } + if (isCompleted) { + this.onCompleted(); + } else { + this.dequeue(); + values = []; + for (i = 0; i < firstValues.length; i++) { + values.push(firstValues[i].value); + } + this.onNext.apply(this, values); + } + } + }; + + /** @private */ + var JoinObserver = (function (_super) { + + inherits(JoinObserver, _super); + + /** + * @constructor + * @private + */ + function JoinObserver(source, onError) { + _super.call(this); + this.source = source; + this.onError = onError; + this.queue = []; + this.activePlans = []; + this.subscription = new SingleAssignmentDisposable(); + this.isDisposed = false; + } + + var JoinObserverPrototype = JoinObserver.prototype; + + /** + * @memberOf JoinObserver# + * @private + */ + JoinObserverPrototype.next = function (notification) { + if (!this.isDisposed) { + if (notification.kind === 'E') { + this.onError(notification.exception); + return; + } + this.queue.push(notification); + var activePlans = this.activePlans.slice(0); + for (var i = 0, len = activePlans.length; i < len; i++) { + activePlans[i].match(); + } + } + }; + + /** + * @memberOf JoinObserver# + * @private + */ + JoinObserverPrototype.error = noop; + + /** + * @memberOf JoinObserver# + * @private + */ + JoinObserverPrototype.completed = noop; + + /** + * @memberOf JoinObserver# + * @private + */ + JoinObserverPrototype.addActivePlan = function (activePlan) { + this.activePlans.push(activePlan); + }; + + /** + * @memberOf JoinObserver# + * @private + */ + JoinObserverPrototype.subscribe = function () { + this.subscription.setDisposable(this.source.materialize().subscribe(this)); + }; + + /** + * @memberOf JoinObserver# + * @private + */ + JoinObserverPrototype.removeActivePlan = function (activePlan) { + var idx = this.activePlans.indexOf(activePlan); + this.activePlans.splice(idx, 1); + if (this.activePlans.length === 0) { + this.dispose(); + } + }; + + /** + * @memberOf JoinObserver# + * @private + */ + JoinObserverPrototype.dispose = function () { + _super.prototype.dispose.call(this); + if (!this.isDisposed) { + this.isDisposed = true; + this.subscription.dispose(); + } + }; + + return JoinObserver; + } (AbstractObserver)); + + /** + * Creates a pattern that matches when both observable sequences have an available value. + * + * @param right Observable sequence to match with the current sequence. + * @return {Pattern} Pattern object that matches when both observable sequences have an available value. + */ + observableProto.and = function (right) { + return new Pattern([this, right]); + }; + + /** + * Matches when the observable sequence has an available value and projects the value. + * + * @param selector Selector that will be invoked for values in the source sequence. + * @returns {Plan} Plan that produces the projected values, to be fed (with other plans) to the when operator. + */ + observableProto.then = function (selector) { + return new Pattern([this]).then(selector); + }; + + /** + * Joins together the results from several patterns. + * + * @param plans A series of plans (specified as an Array of as a series of arguments) created by use of the Then operator on patterns. + * @returns {Observable} Observable sequence with the results form matching several patterns. + */ + Observable.when = function () { + var plans = argsOrArray(arguments, 0); + return new AnonymousObservable(function (observer) { + var activePlans = [], + externalSubscriptions = new Map(), + group, + i, len, + joinObserver, + joinValues, + outObserver; + outObserver = observerCreate(observer.onNext.bind(observer), function (exception) { + var values = externalSubscriptions.getValues(); + for (var j = 0, jlen = values.length; j < jlen; j++) { + values[j].onError(exception); + } + observer.onError(exception); + }, observer.onCompleted.bind(observer)); + try { + for (i = 0, len = plans.length; i < len; i++) { + activePlans.push(plans[i].activate(externalSubscriptions, outObserver, function (activePlan) { + var idx = activePlans.indexOf(activePlan); + activePlans.splice(idx, 1); + if (activePlans.length === 0) { + outObserver.onCompleted(); + } + })); + } + } catch (e) { + observableThrow(e).subscribe(observer); + } + group = new CompositeDisposable(); + joinValues = externalSubscriptions.getValues(); + for (i = 0, len = joinValues.length; i < len; i++) { + joinObserver = joinValues[i]; + joinObserver.subscribe(); + group.add(joinObserver); + } + return group; + }); + }; + + function observableTimerDate(dueTime, scheduler) { + return new AnonymousObservable(function (observer) { + return scheduler.scheduleWithAbsolute(dueTime, function () { + observer.onNext(0); + observer.onCompleted(); + }); + }); + } + + function observableTimerDateAndPeriod(dueTime, period, scheduler) { + var p = normalizeTime(period); + return new AnonymousObservable(function (observer) { + var count = 0, d = dueTime; + return scheduler.scheduleRecursiveWithAbsolute(d, function (self) { + var now; + if (p > 0) { + now = scheduler.now(); + d = d + p; + if (d <= now) { + d = now + p; + } + } + observer.onNext(count++); + self(d); + }); + }); + } + + function observableTimerTimeSpan(dueTime, scheduler) { + var d = normalizeTime(dueTime); + return new AnonymousObservable(function (observer) { + return scheduler.scheduleWithRelative(d, function () { + observer.onNext(0); + observer.onCompleted(); + }); + }); + } + + function observableTimerTimeSpanAndPeriod(dueTime, period, scheduler) { + if (dueTime === period) { + return new AnonymousObservable(function (observer) { + return scheduler.schedulePeriodicWithState(0, period, function (count) { + observer.onNext(count); + return count + 1; + }); + }); + } + return 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) { + scheduler || (scheduler = timeoutScheduler); + return observableTimerTimeSpanAndPeriod(period, period, scheduler); + }; + + /** + * Returns an observable sequence that produces a value after dueTime has elapsed and then after each period. + * + * @example + * 1 - res = Rx.Observable.timer(new Date()); + * 2 - res = Rx.Observable.timer(new Date(), 1000); + * 3 - res = Rx.Observable.timer(new Date(), Rx.Scheduler.timeout); + * 4 - res = Rx.Observable.timer(new Date(), 1000, Rx.Scheduler.timeout); + * + * 5 - res = Rx.Observable.timer(5000); + * 6 - res = Rx.Observable.timer(5000, 1000); + * 7 - res = Rx.Observable.timer(5000, Rx.Scheduler.timeout); + * 8 - res = Rx.Observable.timer(5000, 1000, Rx.Scheduler.timeout); + * + * @param {Number} dueTime Absolute (specified as a Date object) or relative time (specified as an integer denoting milliseconds) at which to produce the first value. + * @param {Mixed} [periodOrScheduler] Period to produce subsequent values (specified as an integer denoting milliseconds), or the scheduler to run the timer on. If not specified, the resulting timer is not recurring. + * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, the timeout scheduler is used. + * @returns {Observable} An observable sequence that produces a value after due time has elapsed and then each period. + */ + var observableTimer = Observable.timer = function (dueTime, periodOrScheduler, scheduler) { + var period; + scheduler || (scheduler = timeoutScheduler); + if (periodOrScheduler !== undefined && typeof periodOrScheduler === 'number') { + period = periodOrScheduler; + } else if (periodOrScheduler !== undefined && typeof periodOrScheduler === 'object') { + scheduler = periodOrScheduler; + } + if (dueTime instanceof Date && period === undefined) { + return observableTimerDate(dueTime.getTime(), scheduler); + } + if (dueTime instanceof Date && period !== undefined) { + period = periodOrScheduler; + return observableTimerDateAndPeriod(dueTime.getTime(), period, scheduler); + } + if (period === undefined) { + return observableTimerTimeSpan(dueTime, scheduler); + } + return observableTimerTimeSpanAndPeriod(dueTime, period, scheduler); + }; + + function observableDelayTimeSpan(dueTime, scheduler) { + var source = this; + return new AnonymousObservable(function (observer) { + var active = false, + cancelable = new SerialDisposable(), + exception = null, + q = [], + running = false, + subscription; + subscription = source.materialize().timestamp(scheduler).subscribe(function (notification) { + var d, shouldRun; + if (notification.value.kind === 'E') { + q = []; + q.push(notification); + exception = notification.value.exception; + shouldRun = !running; + } else { + q.push({ value: notification.value, timestamp: notification.timestamp + dueTime }); + shouldRun = !active; + active = true; + } + if (shouldRun) { + if (exception !== null) { + observer.onError(exception); + } else { + d = new SingleAssignmentDisposable(); + cancelable.setDisposable(d); + d.setDisposable(scheduler.scheduleRecursiveWithRelative(dueTime, function (self) { + var e, recurseDueTime, result, shouldRecurse; + if (exception !== null) { + return; + } + running = true; + do { + result = null; + if (q.length > 0 && q[0].timestamp - scheduler.now() <= 0) { + result = q.shift().value; + } + if (result !== null) { + result.accept(observer); + } + } while (result !== null); + shouldRecurse = false; + recurseDueTime = 0; + if (q.length > 0) { + shouldRecurse = true; + recurseDueTime = Math.max(0, q[0].timestamp - scheduler.now()); + } else { + active = false; + } + e = exception; + running = false; + if (e !== null) { + observer.onError(e); + } else if (shouldRecurse) { + self(recurseDueTime); + } + })); + } + } + }); + return new CompositeDisposable(subscription, cancelable); + }); + } + + function observableDelayDate(dueTime, scheduler) { + var self = this; + return observableDefer(function () { + var timeSpan = dueTime - scheduler.now(); + return observableDelayTimeSpan.call(self, timeSpan, 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) { + scheduler || (scheduler = timeoutScheduler); + return dueTime instanceof Date ? + observableDelayDate.call(this, dueTime.getTime(), scheduler) : + observableDelayTimeSpan.call(this, dueTime, scheduler); + }; + + /** + * Ignores values from an observable sequence which are followed by another value before dueTime. + * + * @example + * 1 - res = source.throttle(5000); // 5 seconds + * 2 - res = source.throttle(5000, scheduler); + * + * @param {Number} dueTime Duration of the throttle period for each value (specified as an integer denoting milliseconds). + * @param {Scheduler} [scheduler] Scheduler to run the throttle timers on. If not specified, the timeout scheduler is used. + * @returns {Observable} The throttled sequence. + */ + observableProto.throttle = function (dueTime, scheduler) { + scheduler || (scheduler = timeoutScheduler); + var source = this; + return this.throttleWithSelector(function () { return observableTimer(dueTime, scheduler); }) + }; + + /** + * Projects each element of an observable sequence into zero or more windows which are produced based on timing information. + * + * @example + * 1 - res = xs.windowWithTime(1000, scheduler); // non-overlapping segments of 1 second + * 2 - res = xs.windowWithTime(1000, 500 , scheduler); // segments of 1 second with time shift 0.5 seconds + * + * @param {Number} timeSpan Length of each window (specified as an integer denoting milliseconds). + * @param {Mixed} [timeShiftOrScheduler] Interval between creation of consecutive windows (specified as an integer denoting milliseconds), or an optional scheduler parameter. If not specified, the time shift corresponds to the timeSpan parameter, resulting in non-overlapping adjacent windows. + * @param {Scheduler} [scheduler] Scheduler to run windowing timers on. If not specified, the timeout scheduler is used. + * @returns {Observable} An observable sequence of windows. + */ + observableProto.windowWithTime = function (timeSpan, timeShiftOrScheduler, scheduler) { + var source = this, timeShift; + if (timeShiftOrScheduler === undefined) { + timeShift = timeSpan; + } + if (scheduler === undefined) { + scheduler = timeoutScheduler; + } + if (typeof timeShiftOrScheduler === 'number') { + timeShift = timeShiftOrScheduler; + } else if (typeof timeShiftOrScheduler === 'object') { + timeShift = timeSpan; + scheduler = timeShiftOrScheduler; + } + return new AnonymousObservable(function (observer) { + var groupDisposable, + nextShift = timeShift, + nextSpan = timeSpan, + q = [], + refCountDisposable, + timerD = new SerialDisposable(), + totalTime = 0; + groupDisposable = new CompositeDisposable(timerD), + refCountDisposable = new RefCountDisposable(groupDisposable); + + 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 () { + var s; + if (isShift) { + s = new Subject(); + q.push(s); + observer.onNext(addRef(s, refCountDisposable)); + } + if (isSpan) { + s = q.shift(); + s.onCompleted(); + } + createTimer(); + })); + }; + q.push(new Subject()); + observer.onNext(addRef(q[0], refCountDisposable)); + createTimer(); + groupDisposable.add(source.subscribe(function (x) { + var i, s; + for (i = 0; i < q.length; i++) { + s = q[i]; + s.onNext(x); + } + }, function (e) { + var i, s; + for (i = 0; i < q.length; i++) { + s = q[i]; + s.onError(e); + } + observer.onError(e); + }, function () { + var i, s; + for (i = 0; i < q.length; i++) { + s = q[i]; + s.onCompleted(); + } + observer.onCompleted(); + })); + return refCountDisposable; + }); + }; + + /** + * Projects each element of an observable sequence into a window that is completed when either it's full or a given amount of time has elapsed. + * @example + * 1 - res = source.windowWithTimeOrCount(5000, 50); // 5s or 50 items + * 2 - res = source.windowWithTimeOrCount(5000, 50, scheduler); //5s or 50 items + * + * @memberOf Observable# + * @param {Number} timeSpan Maximum time length of a window. + * @param {Number} count Maximum element count of a window. + * @param {Scheduler} [scheduler] Scheduler to run windowing timers on. If not specified, the timeout scheduler is used. + * @returns {Observable} An observable sequence of windows. + */ + observableProto.windowWithTimeOrCount = function (timeSpan, count, scheduler) { + var source = this; + scheduler || (scheduler = timeoutScheduler); + return new AnonymousObservable(function (observer) { + var createTimer, + groupDisposable, + n = 0, + refCountDisposable, + s, + timerD = new SerialDisposable(), + windowId = 0; + groupDisposable = new CompositeDisposable(timerD); + refCountDisposable = new RefCountDisposable(groupDisposable); + createTimer = function (id) { + var m = new SingleAssignmentDisposable(); + timerD.setDisposable(m); + m.setDisposable(scheduler.scheduleWithRelative(timeSpan, function () { + var newId; + if (id !== windowId) { + return; + } + n = 0; + newId = ++windowId; + s.onCompleted(); + s = new Subject(); + observer.onNext(addRef(s, refCountDisposable)); + createTimer(newId); + })); + }; + s = new Subject(); + observer.onNext(addRef(s, refCountDisposable)); + createTimer(0); + groupDisposable.add(source.subscribe(function (x) { + var newId = 0, newWindow = false; + s.onNext(x); + n++; + if (n === count) { + newWindow = true; + n = 0; + newId = ++windowId; + s.onCompleted(); + s = new Subject(); + observer.onNext(addRef(s, refCountDisposable)); + } + if (newWindow) { + createTimer(newId); + } + }, function (e) { + s.onError(e); + observer.onError(e); + }, function () { + s.onCompleted(); + observer.onCompleted(); + })); + return refCountDisposable; + }); + }; + + /** + * 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; + scheduler || (scheduler = timeoutScheduler); + return observableDefer(function () { + var last = scheduler.now(); + return source.select(function (x) { + var now = scheduler.now(), span = now - last; + last = now; + return { + value: x, + interval: span + }; + }); + }); + }; + + /** + * Records the timestamp for each value in an observable sequence. + * + * @example + * 1 - res = source.timestamp(); // produces { value: x, timestamp: ts } + * 2 - res = source.timestamp(Rx.Scheduler.timeout); + * + * @param {Scheduler} [scheduler] Scheduler used to compute timestamps. If not specified, the timeout scheduler is used. + * @returns {Observable} An observable sequence with timestamp information on values. + */ + observableProto.timestamp = function (scheduler) { + scheduler || (scheduler = timeoutScheduler); + return this.select(function (x) { + return { + value: x, + timestamp: scheduler.now() + }; + }); + }; + + function sampleObservable(source, sampler) { + + return new AnonymousObservable(function (observer) { + var atEnd, value, hasValue; + + function sampleSubscribe() { + if (hasValue) { + hasValue = false; + observer.onNext(value); + } + if (atEnd) { + observer.onCompleted(); + } + } + + return new CompositeDisposable( + source.subscribe(function (newValue) { + hasValue = true; + value = newValue; + }, observer.onError.bind(observer), function () { + atEnd = true; + }), + sampler.subscribe(sampleSubscribe, observer.onError.bind(observer), sampleSubscribe) + ); + }); + } + + /** + * Samples the observable sequence at each interval. + * + * @example + * 1 - res = source.sample(sampleObservable); // Sampler tick sequence + * 2 - res = source.sample(5000); // 5 seconds + * 2 - res = source.sample(5000, Rx.Scheduler.timeout); // 5 seconds + * + * @param {Mixed} intervalOrSampler Interval at which to sample (specified as an integer denoting milliseconds) or Sampler Observable. + * @param {Scheduler} [scheduler] Scheduler to run the sampling timer on. If not specified, the timeout scheduler is used. + * @returns {Observable} Sampled observable sequence. + */ + observableProto.sample = function (intervalOrSampler, scheduler) { + scheduler || (scheduler = timeoutScheduler); + if (typeof intervalOrSampler === 'number') { + return sampleObservable(this, observableinterval(intervalOrSampler, scheduler)); + } + return sampleObservable(this, intervalOrSampler); + }; + + /** + * Returns the source observable sequence or the other observable sequence if dueTime elapses. + * + * @example + * 1 - res = source.timeout(new Date()); // As a date + * 2 - res = source.timeout(5000); // 5 seconds + * 3 - res = source.timeout(new Date(), Rx.Observable.returnValue(42)); // As a date and timeout observable + * 4 - res = source.timeout(5000, Rx.Observable.returnValue(42)); // 5 seconds and timeout observable + * 5 - res = source.timeout(new Date(), Rx.Observable.returnValue(42), Rx.Scheduler.timeout); // As a date and timeout observable + * 6 - res = source.timeout(5000, Rx.Observable.returnValue(42), Rx.Scheduler.timeout); // 5 seconds and timeout observable + * + * @param {Number} dueTime Absolute (specified as a Date object) or relative time (specified as an integer denoting milliseconds) when a timeout occurs. + * @param {Observable} [other] Sequence to return in case of a timeout. If not specified, a timeout error throwing sequence will be used. + * @param {Scheduler} [scheduler] Scheduler to run the timeout timers on. If not specified, the timeout scheduler is used. + * @returns {Observable} The source sequence switching to the other sequence in case of a timeout. + */ + observableProto.timeout = function (dueTime, other, scheduler) { + other || (other = observableThrow(new Error('Timeout'))); + scheduler || (scheduler = timeoutScheduler); + + var source = this, schedulerMethod = dueTime instanceof Date ? + 'scheduleWithAbsolute' : + 'scheduleWithRelative'; + + return new AnonymousObservable(function (observer) { + var id = 0, + original = new SingleAssignmentDisposable(), + subscription = new SerialDisposable(), + switched = false, + timer = new SerialDisposable(); + + subscription.setDisposable(original); + + var createTimer = function () { + var myId = id; + timer.setDisposable(scheduler[schedulerMethod](dueTime, function () { + if (id === myId) { + isPromise(other) && (other = observableFromPromise(other)); + subscription.setDisposable(other.subscribe(observer)); + } + })); + }; + + createTimer(); + + original.setDisposable(source.subscribe(function (x) { + if (!switched) { + id++; + observer.onNext(x); + createTimer(); + } + }, function (e) { + if (!switched) { + id++; + observer.onError(e); + } + }, function () { + if (!switched) { + id++; + observer.onCompleted(); + } + })); + return new CompositeDisposable(subscription, timer); + }); + }; + + /** + * Generates an observable sequence by iterating a state from an initial state until the condition fails. + * + * @example + * res = source.generateWithAbsoluteTime(0, + * function (x) { return return true; }, + * function (x) { return x + 1; }, + * function (x) { return x; }, + * function (x) { return new Date(); } + * }); + * + * @param {Mixed} initialState Initial state. + * @param {Function} condition Condition to terminate generation (upon returning false). + * @param {Function} iterate Iteration step function. + * @param {Function} resultSelector Selector function for results produced in the sequence. + * @param {Function} timeSelector Time selector function to control the speed of values being produced each iteration, returning Date values. + * @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not specified, the timeout scheduler is used. + * @returns {Observable} The generated sequence. + */ + Observable.generateWithAbsoluteTime = function (initialState, condition, iterate, resultSelector, timeSelector, scheduler) { + scheduler || (scheduler = timeoutScheduler); + return new AnonymousObservable(function (observer) { + var first = true, + hasResult = false, + result, + state = initialState, + time; + return scheduler.scheduleRecursiveWithAbsolute(scheduler.now(), function (self) { + if (hasResult) { + observer.onNext(result); + } + try { + if (first) { + first = false; + } else { + state = iterate(state); + } + hasResult = condition(state); + if (hasResult) { + result = resultSelector(state); + time = timeSelector(state); + } + } catch (e) { + observer.onError(e); + return; + } + if (hasResult) { + self(time); + } else { + observer.onCompleted(); + } + }); + }); + }; + + /** + * Generates an observable sequence by iterating a state from an initial state until the condition fails. + * + * @example + * res = source.generateWithRelativeTime(0, + * function (x) { return return true; }, + * function (x) { return x + 1; }, + * function (x) { return x; }, + * function (x) { return 500; } + * ); + * + * @param {Mixed} initialState Initial state. + * @param {Function} condition Condition to terminate generation (upon returning false). + * @param {Function} iterate Iteration step function. + * @param {Function} resultSelector Selector function for results produced in the sequence. + * @param {Function} timeSelector Time selector function to control the speed of values being produced each iteration, returning integer values denoting milliseconds. + * @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not specified, the timeout scheduler is used. + * @returns {Observable} The generated sequence. + */ + Observable.generateWithRelativeTime = function (initialState, condition, iterate, resultSelector, timeSelector, scheduler) { + scheduler || (scheduler = timeoutScheduler); + return new AnonymousObservable(function (observer) { + var first = true, + hasResult = false, + result, + state = initialState, + time; + return scheduler.scheduleRecursiveWithRelative(0, function (self) { + if (hasResult) { + observer.onNext(result); + } + try { + if (first) { + first = false; + } else { + state = iterate(state); + } + hasResult = condition(state); + if (hasResult) { + result = resultSelector(state); + time = timeSelector(state); + } + } catch (e) { + observer.onError(e); + return; + } + if (hasResult) { + self(time); + } else { + observer.onCompleted(); + } + }); + }); + }; + + /** + * Time shifts the observable sequence by delaying the subscription. + * + * @example + * 1 - res = source.delaySubscription(5000); // 5s + * 2 - res = source.delaySubscription(5000, Rx.Scheduler.timeout); // 5 seconds + * + * @param {Number} dueTime Absolute or relative time to perform the subscription at. + * @param {Scheduler} [scheduler] Scheduler to run the subscription delay timer on. If not specified, the timeout scheduler is used. + * @returns {Observable} Time-shifted sequence. + */ + observableProto.delaySubscription = function (dueTime, scheduler) { + scheduler || (scheduler = timeoutScheduler); + return this.delayWithSelector(observableTimer(dueTime, scheduler), function () { return observableEmpty(); }); + }; + + /** + * Time shifts the observable sequence based on a subscription delay and a delay selector function for each element. + * + * @example + * 1 - res = source.delayWithSelector(function (x) { return Rx.Scheduler.timer(5000); }); // with selector only + * 1 - res = source.delayWithSelector(Rx.Observable.timer(2000), function (x) { return Rx.Observable.timer(x); }); // with delay and selector + * + * @param {Observable} [subscriptionDelay] Sequence indicating the delay for the subscription to the source. + * @param {Function} delayDurationSelector Selector function to retrieve a sequence indicating the delay for each given element. + * @returns {Observable} Time-shifted sequence. + */ + observableProto.delayWithSelector = function (subscriptionDelay, delayDurationSelector) { + var source = this, subDelay, selector; + if (typeof subscriptionDelay === 'function') { + selector = subscriptionDelay; + } else { + subDelay = subscriptionDelay; + selector = delayDurationSelector; + } + return new AnonymousObservable(function (observer) { + var delays = new CompositeDisposable(), atEnd = false, done = function () { + if (atEnd && delays.length === 0) { + observer.onCompleted(); + } + }, subscription = new SerialDisposable(), start = function () { + subscription.setDisposable(source.subscribe(function (x) { + var delay; + try { + delay = selector(x); + } catch (error) { + observer.onError(error); + return; + } + var d = new SingleAssignmentDisposable(); + delays.add(d); + d.setDisposable(delay.subscribe(function () { + observer.onNext(x); + delays.remove(d); + done(); + }, observer.onError.bind(observer), function () { + observer.onNext(x); + delays.remove(d); + done(); + })); + }, observer.onError.bind(observer), function () { + atEnd = true; + subscription.dispose(); + done(); + })); + }; + + if (!subDelay) { + start(); + } else { + subscription.setDisposable(subDelay.subscribe(function () { + start(); + }, observer.onError.bind(observer), function () { start(); })); + } + + return new CompositeDisposable(subscription, delays); + }); + }; + + /** + * Returns the source observable sequence, switching to the other observable sequence if a timeout is signaled. + * + * @example + * 1 - res = source.timeoutWithSelector(Rx.Observable.timer(500)); + * 2 - res = source.timeoutWithSelector(Rx.Observable.timer(500), function (x) { return Rx.Observable.timer(200); }); + * 3 - res = source.timeoutWithSelector(Rx.Observable.timer(500), function (x) { return Rx.Observable.timer(200); }, Rx.Observable.returnValue(42)); + * + * @param {Observable} [firstTimeout] Observable sequence that represents the timeout for the first element. If not provided, this defaults to Observable.never(). + * @param {Function} [timeoutDurationSelector] Selector to retrieve an observable sequence that represents the timeout between the current element and the next element. + * @param {Observable} [other] Sequence to return in case of a timeout. If not provided, this is set to Observable.throwException(). + * @returns {Observable} The source sequence switching to the other sequence in case of a timeout. + */ + observableProto.timeoutWithSelector = function (firstTimeout, timeoutdurationSelector, other) { + if (arguments.length === 1) { + timeoutdurationSelector = firstTimeout; + var firstTimeout = observableNever(); + } + other || (other = observableThrow(new Error('Timeout'))); + var source = this; + return new AnonymousObservable(function (observer) { + var subscription = new SerialDisposable(), timer = new SerialDisposable(), original = new SingleAssignmentDisposable(); + + subscription.setDisposable(original); + + var id = 0, switched = false, setTimer = function (timeout) { + var myId = id, timerWins = function () { + return id === myId; + }; + var d = new SingleAssignmentDisposable(); + timer.setDisposable(d); + d.setDisposable(timeout.subscribe(function () { + if (timerWins()) { + subscription.setDisposable(other.subscribe(observer)); + } + d.dispose(); + }, function (e) { + if (timerWins()) { + observer.onError(e); + } + }, function () { + if (timerWins()) { + subscription.setDisposable(other.subscribe(observer)); + } + })); + }; + + setTimer(firstTimeout); + var observerWins = function () { + var res = !switched; + if (res) { + id++; + } + return res; + }; + + original.setDisposable(source.subscribe(function (x) { + if (observerWins()) { + observer.onNext(x); + var timeout; + try { + timeout = timeoutdurationSelector(x); + } catch (e) { + observer.onError(e); + return; + } + setTimer(timeout); + } + }, function (e) { + if (observerWins()) { + observer.onError(e); + } + }, function () { + if (observerWins()) { + observer.onCompleted(); + } + })); + return new CompositeDisposable(subscription, timer); + }); + }; + + /** + * Ignores values from an observable sequence which are followed by another value within a computed throttle duration. + * + * @example + * 1 - res = source.delayWithSelector(function (x) { return Rx.Scheduler.timer(x + x); }); + * + * @param {Function} throttleDurationSelector Selector function to retrieve a sequence indicating the throttle duration for each given element. + * @returns {Observable} The throttled sequence. + */ + observableProto.throttleWithSelector = function (throttleDurationSelector) { + var source = this; + return new AnonymousObservable(function (observer) { + var value, hasValue = false, cancelable = new SerialDisposable(), id = 0, subscription = source.subscribe(function (x) { + var throttle; + try { + throttle = throttleDurationSelector(x); + } catch (e) { + observer.onError(e); + return; + } + hasValue = true; + value = x; + id++; + var currentid = id, d = new SingleAssignmentDisposable(); + cancelable.setDisposable(d); + d.setDisposable(throttle.subscribe(function () { + if (hasValue && id === currentid) { + observer.onNext(value); + } + hasValue = false; + d.dispose(); + }, observer.onError.bind(observer), function () { + if (hasValue && id === currentid) { + observer.onNext(value); + } + hasValue = false; + d.dispose(); + })); + }, function (e) { + cancelable.dispose(); + observer.onError(e); + hasValue = false; + id++; + }, function () { + cancelable.dispose(); + if (hasValue) { + observer.onNext(value); + } + observer.onCompleted(); + hasValue = false; + id++; + }); + return new CompositeDisposable(subscription, cancelable); + }); + }; + + /** + * Skips elements for the specified duration from the end of the observable source sequence, using the specified scheduler to run timers. + * + * 1 - res = source.skipLastWithTime(5000); + * 2 - res = source.skipLastWithTime(5000, scheduler); + * + * @description + * This operator accumulates a queue with a length enough to store elements received during the initial duration window. + * As more elements are received, elements older than the specified duration are taken from the queue and produced on the + * result sequence. This causes elements to be delayed with duration. + * @param {Number} duration Duration for skipping elements from the end of the sequence. + * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout + * @returns {Observable} An observable sequence with the elements skipped during the specified duration from the end of the source sequence. + */ + observableProto.skipLastWithTime = function (duration, scheduler) { + scheduler || (scheduler = timeoutScheduler); + var source = this; + return new AnonymousObservable(function (observer) { + var q = []; + return source.subscribe(function (x) { + var now = scheduler.now(); + q.push({ interval: now, value: x }); + while (q.length > 0 && now - q[0].interval >= duration) { + observer.onNext(q.shift().value); + } + }, observer.onError.bind(observer), function () { + var now = scheduler.now(); + while (q.length > 0 && now - q[0].interval >= duration) { + observer.onNext(q.shift().value); + } + observer.onCompleted(); + }); + }); + }; + + /** + * Returns elements within the specified duration from the end of the observable source sequence, using the specified schedulers to run timers and to drain the collected elements. + * + * @example + * 1 - res = source.takeLastWithTime(5000, [optional timer scheduler], [optional loop scheduler]); + * @description + * This operator accumulates a queue with a length enough to store elements received during the initial duration window. + * As more elements are received, elements older than the specified duration are taken from the queue and produced on the + * result sequence. This causes elements to be delayed with duration. + * @param {Number} duration Duration for taking elements from the end of the sequence. + * @param {Scheduler} [timerScheduler] Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. + * @param {Scheduler} [loopScheduler] Scheduler to drain the collected elements. If not specified, defaults to Rx.Scheduler.immediate. + * @returns {Observable} An observable sequence with the elements taken during the specified duration from the end of the source sequence. + */ + observableProto.takeLastWithTime = function (duration, timerScheduler, loopScheduler) { + return this.takeLastBufferWithTime(duration, timerScheduler).selectMany(function (xs) { return observableFromArray(xs, loopScheduler); }); + }; + + /** + * Returns an array with the elements within the specified duration from the end of the observable source sequence, using the specified scheduler to run timers. + * + * @example + * 1 - res = source.takeLastBufferWithTime(5000, [optional scheduler]); + * @description + * This operator accumulates a queue with a length enough to store elements received during the initial duration window. + * As more elements are received, elements older than the specified duration are taken from the queue and produced on the + * result sequence. This causes elements to be delayed with duration. + * @param {Number} duration Duration for taking elements from the end of the sequence. + * @param {Scheduler} scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. + * @returns {Observable} An observable sequence containing a single array with the elements taken during the specified duration from the end of the source sequence. + */ + observableProto.takeLastBufferWithTime = function (duration, scheduler) { + var source = this; + scheduler || (scheduler = timeoutScheduler); + return new AnonymousObservable(function (observer) { + var q = []; + + return source.subscribe(function (x) { + var now = scheduler.now(); + q.push({ interval: now, value: x }); + while (q.length > 0 && now - q[0].interval >= duration) { + q.shift(); + } + }, observer.onError.bind(observer), function () { + var now = scheduler.now(), res = []; + while (q.length > 0) { + var next = q.shift(); + if (now - next.interval <= duration) { + res.push(next.value); + } + } + + observer.onNext(res); + observer.onCompleted(); + }); + }); + }; + + /** + * Takes elements for the specified duration from the start of the observable source sequence, using the specified scheduler to run timers. + * + * @example + * 1 - res = source.takeWithTime(5000, [optional scheduler]); + * @description + * This operator accumulates a queue with a length enough to store elements received during the initial duration window. + * As more elements are received, elements older than the specified duration are taken from the queue and produced on the + * result sequence. This causes elements to be delayed with duration. + * @param {Number} duration Duration for taking elements from the start of the sequence. + * @param {Scheduler} scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. + * @returns {Observable} An observable sequence with the elements taken during the specified duration from the start of the source sequence. + */ + observableProto.takeWithTime = function (duration, scheduler) { + var source = this; + scheduler || (scheduler = timeoutScheduler); + return new AnonymousObservable(function (observer) { + var t = scheduler.scheduleWithRelative(duration, function () { + observer.onCompleted(); + }); + + return new CompositeDisposable(t, source.subscribe(observer)); + }); + }; + + /** + * Skips elements for the specified duration from the start of the observable source sequence, using the specified scheduler to run timers. + * + * @example + * 1 - res = source.skipWithTime(5000, [optional scheduler]); + * + * @description + * Specifying a zero value for duration doesn't guarantee no elements will be dropped from the start of the source sequence. + * This is a side-effect of the asynchrony introduced by the scheduler, where the action that causes callbacks from the source sequence to be forwarded + * may not execute immediately, despite the zero due time. + * + * Errors produced by the source sequence are always forwarded to the result sequence, even if the error occurs before the duration. + * @param {Number} duration Duration for skipping elements from the start of the sequence. + * @param {Scheduler} scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. + * @returns {Observable} An observable sequence with the elements skipped during the specified duration from the start of the source sequence. + */ + observableProto.skipWithTime = function (duration, scheduler) { + var source = this; + scheduler || (scheduler = timeoutScheduler); + return new AnonymousObservable(function (observer) { + var open = false, + t = scheduler.scheduleWithRelative(duration, function () { open = true; }), + d = source.subscribe(function (x) { + if (open) { + observer.onNext(x); + } + }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); + + return new CompositeDisposable(t, d); + }); + }; + + /** + * Skips elements from the observable source sequence until the specified start time, using the specified scheduler to run timers. + * Errors produced by the source sequence are always forwarded to the result sequence, even if the error occurs before the start time. + * + * @examples + * 1 - res = source.skipUntilWithTime(new Date(), [optional scheduler]); + * 2 - res = source.skipUntilWithTime(5000, [optional scheduler]); + * @param startTime Time to start taking elements from the source sequence. If this value is less than or equal to Date(), no elements will be skipped. + * @param scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. + * @returns {Observable} An observable sequence with the elements skipped until the specified start time. + */ + observableProto.skipUntilWithTime = function (startTime, scheduler) { + scheduler || (scheduler = timeoutScheduler); + var source = this, schedulerMethod = startTime instanceof Date ? + 'scheduleWithAbsolute' : + 'scheduleWithRelative'; + return new AnonymousObservable(function (observer) { + var open = false; + + return new CompositeDisposable( + scheduler[schedulerMethod](startTime, function () { open = true; }), + source.subscribe( + function (x) { open && observer.onNext(x); }, + observer.onError.bind(observer), + observer.onCompleted.bind(observer))); + }); + }; + + /** + * Takes elements for the specified duration until the specified end time, using the specified scheduler to run timers. + * + * @example + * 1 - res = source.takeUntilWithTime(new Date(), [optional scheduler]); + * 2 - res = source.takeUntilWithTime(5000, [optional scheduler]); + * @param {Number | Date} endTime Time to stop taking elements from the source sequence. If this value is less than or equal to new Date(), the result stream will complete immediately. + * @param {Scheduler} scheduler Scheduler to run the timer on. + * @returns {Observable} An observable sequence with the elements taken until the specified end time. + */ + observableProto.takeUntilWithTime = function (endTime, scheduler) { + scheduler || (scheduler = timeoutScheduler); + var source = this, schedulerMethod = endTime instanceof Date ? + 'scheduleWithAbsolute' : + 'scheduleWithRelative'; + return new AnonymousObservable(function (observer) { + return new CompositeDisposable(scheduler[schedulerMethod](endTime, function () { + observer.onCompleted(); + }), source.subscribe(observer)); + }); + }; + + /* + * Performs a exclusive waiting for the first to finish before subscribing to another observable. + * Observables that come in between subscriptions will be dropped on the floor. + * @returns {Observable} A exclusive observable with only the results that happen when subscribed. + */ + observableProto.exclusive = function () { + var sources = this; + return new AnonymousObservable(function (observer) { + var hasCurrent = false, + isStopped = false, + m = new SingleAssignmentDisposable(), + g = new CompositeDisposable(); + + g.add(m); + + m.setDisposable(sources.subscribe( + function (innerSource) { + if (!hasCurrent) { + hasCurrent = true; + + isPromise(innerSource) && (innerSource = observableFromPromise(innerSource)); + + var innerSubscription = new SingleAssignmentDisposable(); + g.add(innerSubscription); + + innerSubscription.setDisposable(innerSource.subscribe( + observer.onNext.bind(observer), + observer.onError.bind(observer), + function () { + g.remove(innerSubscription); + hasCurrent = false; + if (isStopped && g.length === 1) { + observer.onCompleted(); + } + })); + } + }, + observer.onError.bind(observer), + function () { + isStopped = true; + if (!hasCurrent && g.length === 1) { + observer.onCompleted(); + } + })); + + return g; + }); + }; + /* + * Performs a exclusive map waiting for the first to finish before subscribing to another observable. + * Observables that come in between subscriptions will be dropped on the floor. + * @param {Function} selector Selector to invoke for every item in the current subscription. + * @param {Any} [thisArg] An optional context to invoke with the selector parameter. + * @returns {Observable} An exclusive observable with only the results that happen when subscribed. + */ + observableProto.exclusiveMap = function (selector, thisArg) { + var sources = this; + return new AnonymousObservable(function (observer) { + var index = 0, + hasCurrent = false, + isStopped = true, + m = new SingleAssignmentDisposable(), + g = new CompositeDisposable(); + + g.add(m); + + m.setDisposable(sources.subscribe( + function (innerSource) { + + if (!hasCurrent) { + hasCurrent = true; + + innerSubscription = new SingleAssignmentDisposable(); + g.add(innerSubscription); + + isPromise(innerSource) && (innerSource = observableFromPromise(innerSource)); + + innerSubscription.setDisposable(innerSource.subscribe( + function (x) { + var result; + try { + result = selector.call(thisArg, x, index++, innerSource); + } catch (e) { + observer.onError(e); + return; + } + + observer.onNext(result); + }, + observer.onError.bind(observer), + function () { + g.remove(innerSubscription); + hasCurrent = false; + + if (isStopped && g.length === 1) { + observer.onCompleted(); + } + })); + } + }, + observer.onError.bind(observer), + function () { + isStopped = true; + if (g.length === 1 && !hasCurrent) { + observer.onCompleted(); + } + })); + return g; + }); + }; + /** Provides a set of extension methods for virtual time scheduling. */ + Rx.VirtualTimeScheduler = (function (_super) { + + function notImplemented() { + throw new Error('Not implemented'); + } + + function localNow() { + return this.toDateTimeOffset(this.clock); + } + + function scheduleNow(state, action) { + return this.scheduleAbsoluteWithState(state, this.clock, action); + } + + function scheduleRelative(state, dueTime, action) { + return this.scheduleRelativeWithState(state, this.toRelative(dueTime), action); + } + + function scheduleAbsolute(state, dueTime, action) { + return this.scheduleRelativeWithState(state, this.toRelative(dueTime - this.now()), action); + } + + function invokeAction(scheduler, action) { + action(); + return disposableEmpty; + } + + inherits(VirtualTimeScheduler, _super); + + /** + * Creates a new virtual time scheduler with the specified initial clock value and absolute time comparer. + * + * @constructor + * @param {Number} initialClock Initial value for the clock. + * @param {Function} comparer Comparer to determine causality of events based on absolute time. + */ + function VirtualTimeScheduler(initialClock, comparer) { + this.clock = initialClock; + this.comparer = comparer; + this.isEnabled = false; + this.queue = new PriorityQueue(1024); + _super.call(this, localNow, scheduleNow, scheduleRelative, scheduleAbsolute); + } + + var VirtualTimeSchedulerPrototype = VirtualTimeScheduler.prototype; + + /** + * Adds a relative time value to an absolute time value. + * @param {Number} absolute Absolute virtual time value. + * @param {Number} relative Relative virtual time value to add. + * @return {Number} Resulting absolute virtual time sum value. + */ + VirtualTimeSchedulerPrototype.add = notImplemented; + + /** + * Converts an absolute time to a number + * @param {Any} The absolute time. + * @returns {Number} The absolute time in ms + */ + VirtualTimeSchedulerPrototype.toDateTimeOffset = notImplemented; + + /** + * Converts the TimeSpan value to a relative virtual time value. + * @param {Number} timeSpan TimeSpan value to convert. + * @return {Number} Corresponding relative virtual time value. + */ + VirtualTimeSchedulerPrototype.toRelative = notImplemented; + + /** + * Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be emulated using recursive scheduling. + * @param {Mixed} state Initial state passed to the action upon the first iteration. + * @param {Number} period Period for running the work periodically. + * @param {Function} action Action to be executed, potentially updating the state. + * @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort). + */ + VirtualTimeSchedulerPrototype.schedulePeriodicWithState = function (state, period, action) { + var s = new SchedulePeriodicRecursive(this, state, period, action); + return s.start(); + }; + + /** + * Schedules an action to be executed after dueTime. + * @param {Mixed} state State passed to the action to be executed. + * @param {Number} dueTime Relative time after which to execute the action. + * @param {Function} action Action to be executed. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + VirtualTimeSchedulerPrototype.scheduleRelativeWithState = function (state, dueTime, action) { + var runAt = this.add(this.clock, dueTime); + return this.scheduleAbsoluteWithState(state, runAt, action); + }; + + /** + * Schedules an action to be executed at dueTime. + * @param {Number} dueTime Relative time after which to execute the action. + * @param {Function} action Action to be executed. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + VirtualTimeSchedulerPrototype.scheduleRelative = function (dueTime, action) { + return this.scheduleRelativeWithState(action, dueTime, invokeAction); + }; + + /** + * Starts the virtual time scheduler. + */ + VirtualTimeSchedulerPrototype.start = function () { + var next; + if (!this.isEnabled) { + this.isEnabled = true; + do { + next = this.getNext(); + if (next !== null) { + if (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 next; + var dueToClock = this.comparer(this.clock, time); + if (this.comparer(this.clock, time) > 0) { + throw new Error(argumentOutOfRange); + } + if (dueToClock === 0) { + return; + } + if (!this.isEnabled) { + this.isEnabled = true; + do { + next = this.getNext(); + if (next !== null && this.comparer(next.dueTime, time) <= 0) { + if (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); + var dueToClock = this.comparer(this.clock, dt); + if (dueToClock > 0) { + throw new Error(argumentOutOfRange); + } + if (dueToClock === 0) { + return; + } + this.advanceTo(dt); + }; + + /** + * Advances the scheduler's clock by the specified relative time. + * @param {Number} time Relative time to advance the scheduler's clock by. + */ + VirtualTimeSchedulerPrototype.sleep = function (time) { + var dt = this.add(this.clock, time); + + if (this.comparer(this.clock, dt) >= 0) { + throw new Error(argumentOutOfRange); + } + + this.clock = dt; + }; + + /** + * Gets the next scheduled item to be executed. + * @returns {ScheduledItem} The next scheduled item. + */ + VirtualTimeSchedulerPrototype.getNext = function () { + var next; + while (this.queue.length > 0) { + 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, + run = function (scheduler, state1) { + self.queue.remove(si); + return action(scheduler, state1); + }, + si = new ScheduledItem(self, state, run, dueTime, self.comparer); + self.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; + }; + + /** + * @private + */ + HistoricalSchedulerProto.toDateTimeOffset = function (absolute) { + return new Date(absolute).getTime(); + }; + + /** + * Converts the TimeSpan value to a relative virtual time value. + * + * @memberOf HistoricalScheduler + * @param {Number} timeSpan TimeSpan value to convert. + * @return {Number} Corresponding relative virtual time value. + */ + HistoricalSchedulerProto.toRelative = function (timeSpan) { + return timeSpan; + }; + + return HistoricalScheduler; + }(Rx.VirtualTimeScheduler)); + var AnonymousObservable = Rx.AnonymousObservable = (function (__super__) { + inherits(AnonymousObservable, __super__); + + // Fix subscriber to check for undefined or function returned to decorate as Disposable + function fixSubscriber(subscriber) { + if (typeof subscriber === 'undefined') { + subscriber = disposableEmpty; + } else if (typeof subscriber === 'function') { + subscriber = disposableCreate(subscriber); + } + + return subscriber; + } + + function AnonymousObservable(subscribe) { + if (!(this instanceof AnonymousObservable)) { + return new AnonymousObservable(subscribe); + } + + function s(observer) { + var setDisposable = function () { + try { + autoDetachObserver.setDisposable(fixSubscriber(subscribe(autoDetachObserver))); + } catch (e) { + if (!autoDetachObserver.fail(e)) { + throw e; + } + } + }; + + var autoDetachObserver = new AutoDetachObserver(observer); + if (currentThreadScheduler.scheduleRequired()) { + currentThreadScheduler.schedule(setDisposable); + } else { + setDisposable(); + } + + return autoDetachObserver; + } + + __super__.call(this, s); + } + + return AnonymousObservable; + + }(Observable)); + + /** @private */ + var AutoDetachObserver = (function (_super) { + inherits(AutoDetachObserver, _super); + + function AutoDetachObserver(observer) { + _super.call(this); + this.observer = observer; + this.m = new SingleAssignmentDisposable(); + } + + var AutoDetachObserverPrototype = AutoDetachObserver.prototype; + + AutoDetachObserverPrototype.next = function (value) { + var noError = false; + try { + this.observer.onNext(value); + noError = true; + } catch (e) { + throw e; + } finally { + if (!noError) { + this.dispose(); + } + } + }; + + AutoDetachObserverPrototype.error = function (exn) { + try { + this.observer.onError(exn); + } catch (e) { + throw e; + } finally { + this.dispose(); + } + }; + + AutoDetachObserverPrototype.completed = function () { + try { + this.observer.onCompleted(); + } catch (e) { + throw e; + } finally { + this.dispose(); + } + }; + + AutoDetachObserverPrototype.setDisposable = function (value) { this.m.setDisposable(value); }; + AutoDetachObserverPrototype.getDisposable = function (value) { return this.m.getDisposable(); }; + /* @private */ + AutoDetachObserverPrototype.disposable = function (value) { + return arguments.length ? this.getDisposable() : setDisposable(value); + }; + + AutoDetachObserverPrototype.dispose = function () { + _super.prototype.dispose.call(this); + this.m.dispose(); + }; + + return AutoDetachObserver; + }(AbstractObserver)); + + /** @private */ + var GroupedObservable = (function (_super) { + inherits(GroupedObservable, _super); + + function subscribe(observer) { + return this.underlyingObservable.subscribe(observer); + } + + /** + * @constructor + * @private + */ + function GroupedObservable(key, underlyingObservable, mergedDisposable) { + _super.call(this, subscribe); + this.key = key; + this.underlyingObservable = !mergedDisposable ? + underlyingObservable : + new AnonymousObservable(function (observer) { + return new CompositeDisposable(mergedDisposable.getDisposable(), underlyingObservable.subscribe(observer)); + }); + } + + return GroupedObservable; + }(Observable)); + + /** + * Represents an object that is both an observable sequence as well as an observer. + * Each notification is broadcasted to all subscribed observers. + */ + var Subject = Rx.Subject = (function (_super) { + function subscribe(observer) { + checkDisposed.call(this); + if (!this.isStopped) { + this.observers.push(observer); + return new InnerSubscription(this, observer); + } + if (this.exception) { + observer.onError(this.exception); + return disposableEmpty; + } + observer.onCompleted(); + return disposableEmpty; + } + + inherits(Subject, _super); + + /** + * Creates a subject. + * @constructor + */ + function Subject() { + _super.call(this, subscribe); + this.isDisposed = false, + this.isStopped = false, + this.observers = []; + } + + addProperties(Subject.prototype, Observer, { + /** + * Indicates whether the subject has observers subscribed to it. + * @returns {Boolean} Indicates whether the subject has observers subscribed to it. + */ + hasObservers: function () { + return this.observers.length > 0; + }, + /** + * Notifies all subscribed observers about the end of the sequence. + */ + onCompleted: function () { + checkDisposed.call(this); + if (!this.isStopped) { + var os = this.observers.slice(0); + this.isStopped = true; + for (var i = 0, len = os.length; i < len; i++) { + os[i].onCompleted(); + } + + this.observers = []; + } + }, + /** + * Notifies all subscribed observers about the exception. + * @param {Mixed} error The exception to send to all observers. + */ + onError: function (exception) { + checkDisposed.call(this); + if (!this.isStopped) { + var os = this.observers.slice(0); + this.isStopped = true; + this.exception = exception; + for (var i = 0, len = os.length; i < len; i++) { + os[i].onError(exception); + } + + this.observers = []; + } + }, + /** + * Notifies all subscribed observers about the arrival of the specified element in the sequence. + * @param {Mixed} value The value to send to all observers. + */ + onNext: function (value) { + checkDisposed.call(this); + if (!this.isStopped) { + var os = this.observers.slice(0); + for (var i = 0, len = os.length; i < len; i++) { + os[i].onNext(value); + } + } + }, + /** + * Unsubscribe all observers and release resources. + */ + dispose: function () { + this.isDisposed = true; + this.observers = null; + } + }); + + /** + * Creates a subject from the specified observer and observable. + * @param {Observer} observer The observer used to send messages to the subject. + * @param {Observable} observable The observable used to subscribe to messages sent from the subject. + * @returns {Subject} Subject implemented using the given observer and observable. + */ + Subject.create = function (observer, observable) { + return new AnonymousSubject(observer, observable); + }; + + return Subject; + }(Observable)); + + /** + * Represents the result of an asynchronous operation. + * The last value before the OnCompleted notification, or the error received through OnError, is sent to all subscribed observers. + */ + var AsyncSubject = Rx.AsyncSubject = (function (_super) { + + function subscribe(observer) { + checkDisposed.call(this); + + if (!this.isStopped) { + this.observers.push(observer); + return new InnerSubscription(this, observer); + } + + var ex = this.exception, + hv = this.hasValue, + v = this.value; + + if (ex) { + observer.onError(ex); + } else if (hv) { + observer.onNext(v); + observer.onCompleted(); + } else { + observer.onCompleted(); + } + + return disposableEmpty; + } + + inherits(AsyncSubject, _super); + + /** + * Creates a subject that can only receive one value and that value is cached for all future observations. + * @constructor + */ + function AsyncSubject() { + _super.call(this, subscribe); + + this.isDisposed = false; + this.isStopped = false; + this.value = null; + this.hasValue = false; + this.observers = []; + this.exception = null; + } + + addProperties(AsyncSubject.prototype, Observer, { + /** + * Indicates whether the subject has observers subscribed to it. + * @returns {Boolean} Indicates whether the subject has observers subscribed to it. + */ + hasObservers: function () { + checkDisposed.call(this); + return this.observers.length > 0; + }, + /** + * Notifies all subscribed observers about the end of the sequence, also causing the last received value to be sent out (if any). + */ + onCompleted: function () { + var o, i, len; + checkDisposed.call(this); + if (!this.isStopped) { + this.isStopped = true; + var os = this.observers.slice(0), + v = this.value, + hv = this.hasValue; + + if (hv) { + for (i = 0, len = os.length; i < len; i++) { + o = os[i]; + o.onNext(v); + o.onCompleted(); + } + } else { + for (i = 0, len = os.length; i < len; i++) { + os[i].onCompleted(); + } + } + + this.observers = []; + } + }, + /** + * Notifies all subscribed observers about the exception. + * @param {Mixed} error The exception to send to all observers. + */ + onError: function (exception) { + checkDisposed.call(this); + if (!this.isStopped) { + var os = this.observers.slice(0); + this.isStopped = true; + this.exception = exception; + + for (var i = 0, len = os.length; i < len; i++) { + os[i].onError(exception); + } + + this.observers = []; + } + }, + /** + * Sends a value to the subject. The last value received before successful termination will be sent to all subscribed and future observers. + * @param {Mixed} value The value to store in the subject. + */ + onNext: function (value) { + checkDisposed.call(this); + if (!this.isStopped) { + this.value = value; + this.hasValue = true; + } + }, + /** + * Unsubscribe all observers and release resources. + */ + dispose: function () { + this.isDisposed = true; + this.observers = null; + this.exception = null; + this.value = null; + } + }); + + return AsyncSubject; + }(Observable)); + + /** @private */ + var AnonymousSubject = (function (_super) { + inherits(AnonymousSubject, _super); + + function subscribe(observer) { + return this.observable.subscribe(observer); + } + + /** + * @private + * @constructor + */ + function AnonymousSubject(observer, observable) { + _super.call(this, subscribe); + this.observer = observer; + this.observable = observable; + } + + addProperties(AnonymousSubject.prototype, Observer, { + /** + * @private + * @memberOf AnonymousSubject# + */ + onCompleted: function () { + this.observer.onCompleted(); + }, + /** + * @private + * @memberOf AnonymousSubject# + */ + onError: function (exception) { + this.observer.onError(exception); + }, + /** + * @private + * @memberOf AnonymousSubject# + */ + onNext: function (value) { + this.observer.onNext(value); + } + }); + + return AnonymousSubject; + }(Observable)); + + if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) { + root.Rx = Rx; + + define(function() { + return Rx; + }); + } else if (freeExports && freeModule) { + // in Node.js or RingoJS + if (moduleExports) { + (freeModule.exports = Rx).Rx = Rx; + } else { + freeExports.Rx = Rx; + } + } else { + // in a browser or Rhino + root.Rx = Rx; + } +}.call(this)); \ No newline at end of file diff --git a/ajax/libs/rxjs/2.2.28/rx.all.compat.min.js b/ajax/libs/rxjs/2.2.28/rx.all.compat.min.js new file mode 100644 index 000000000..4644279ba --- /dev/null +++ b/ajax/libs/rxjs/2.2.28/rx.all.compat.min.js @@ -0,0 +1,3 @@ +(function(t){function e(){if(this.isDisposed)throw Error(fe)}function n(t){var e=typeof t;return t&&("function"==e||"object"==e)||!1}function r(t){var e=[];if(!n(t))return e;Pe.nonEnumArgs&&t.length&&u(t)&&(t=Ve.call(t));var r=Pe.enumPrototypes&&"function"==typeof t,i=Pe.enumErrorProps&&(t===Oe||t instanceof Error);for(var o in t)r&&"prototype"==o||i&&("message"==o||"name"==o)||e.push(o);if(Pe.nonEnumShadows&&t!==We){var s=t.constructor,c=-1,a=Re.length;if(t===(s&&s.prototype))var h=t===stringProto?Se:t===Oe?ge:Ne.call(t),l=qe[h];for(;a>++c;)o=Re[c],l&&l[o]||!Ae.call(t,o)||e.push(o)}return e}function i(t,e,n){for(var r=-1,i=n(t),o=i.length;o>++r;){var s=i[r];if(e(t[s],s,t)===!1)break}return t}function o(t,e){return i(t,e,r)}function s(t){return"function"!=typeof t.toString&&"string"==typeof(t+"")}function u(t){return t&&"object"==typeof t?Ne.call(t)==be:!1}function c(t){return"function"==typeof t||!1}function a(e,n,r,i){if(e===n)return 0!==e||1/e==1/n;var h=typeof e,l=typeof n;if(e===e&&(null==e||null==n||"function"!=h&&"object"!=h&&"function"!=l&&"object"!=l))return!1;var f=Ne.call(e),p=Ne.call(n);if(f==be&&(f=Ce),p==be&&(p=Ce),f!=p)return!1;switch(f){case ye:case we:return+e==+n;case xe:return e!=+e?n!=+n:0==e?1/e==1/n:e==+n;case De:case Se:return e==n+""}var d=f==me;if(!d){if(f!=Ce||!Pe.nodeClass&&(s(e)||s(n)))return!1;var v=!Pe.argsObject&&u(e)?Object:e.constructor,b=!Pe.argsObject&&u(n)?Object:n.constructor;if(!(v==b||Ae.call(e,"constructor")&&Ae.call(n,"constructor")||c(v)&&v instanceof v&&c(b)&&b instanceof b||!("constructor"in e&&"constructor"in n)))return!1}r||(r=[]),i||(i=[]);for(var m=r.length;m--;)if(r[m]==e)return i[m]==n;var y=0;if(result=!0,r.push(e),i.push(n),d){if(m=e.length,y=n.length,result=y==m)for(;y--;){var w=n[y];if(!(result=a(e[y],w,r,i)))break}}else o(n,function(n,o,s){return Ae.call(s,o)?(y++,result=Ae.call(e,o)&&a(e[o],n,r,i)):t}),result&&o(e,function(e,n,r){return Ae.call(r,n)?result=--y>-1:t});return r.pop(),i.pop(),result}function h(t,e){return 1===t.length&&Array.isArray(t[e])?t[e]:Ve.call(t)}function l(t,e){for(var n=Array(t),r=0;t>r;r++)n[r]=e();return n}function f(t,e){this.scheduler=t,this.disposable=e,this.isDisposed=!1}function p(e,n){return new hr(function(r){var i=new Ge,o=new Ye;return o.setDisposable(i),i.setDisposable(e.subscribe(r.onNext.bind(r),function(e){var i,s;try{s=n(e)}catch(u){return r.onError(u),t}ae(s)&&(s=On(s)),i=new Ge,o.setDisposable(i),i.setDisposable(s.subscribe(r))},r.onCompleted.bind(r))),o})}function d(e,n){var r=this;return new hr(function(i){var o=0,s=e.length;return r.subscribe(function(r){if(s>o){var u,c=e[o++];try{u=n(r,c)}catch(a){return i.onError(a),t}i.onNext(u)}else i.onCompleted()},i.onError.bind(i),i.onCompleted.bind(i))})}function v(t){return this.map(function(e,n){var r=t(e,n);return ae(r)?On(r):r}).concatAll()}function b(t){return this.select(function(e,n){var r=t(e,n);return ae(r)?On(r):r}).mergeObservable()}function m(e,n,r){return new hr(function(i){var o=!1,s=null,u=[];return e.subscribe(function(e){var c,a;try{a=n(e)}catch(h){return i.onError(h),t}if(c=0,o)try{c=r(a,s)}catch(l){return i.onError(l),t}else o=!0,s=a;c>0&&(s=a,u=[]),c>=0&&u.push(e)},i.onError.bind(i),function(){i.onNext(u),i.onCompleted()})})}function y(t){if(0===t.length)throw Error(he);return t[0]}function w(e,n,r){return new hr(function(i){var o=0,s=n.length;return e.subscribe(function(e){var u=!1;try{s>o&&(u=r(e,n[o++]))}catch(c){return i.onError(c),t}u||(i.onNext(!1),i.onCompleted())},i.onError.bind(i),function(){i.onNext(o===s),i.onCompleted()})})}function g(t,e,n,r){if(0>e)throw Error(le);return new hr(function(i){var o=e;return t.subscribe(function(t){0===o&&(i.onNext(t),i.onCompleted()),o--},i.onError.bind(i),function(){n?(i.onNext(r),i.onCompleted()):i.onError(Error(le))})})}function E(t,e,n){return new hr(function(r){var i=n,o=!1;return t.subscribe(function(t){o?r.onError(Error("Sequence contains more than one element")):(i=t,o=!0)},r.onError.bind(r),function(){o||e?(r.onNext(i),r.onCompleted()):r.onError(Error(he))})})}function x(t,e,n){return new hr(function(r){return t.subscribe(function(t){r.onNext(t),r.onCompleted()},r.onError.bind(r),function(){e?(r.onNext(n),r.onCompleted()):r.onError(Error(he))})})}function C(t,e,n){return new hr(function(r){var i=n,o=!1;return t.subscribe(function(t){i=t,o=!0},r.onError.bind(r),function(){o||e?(r.onNext(i),r.onCompleted()):r.onError(Error(he))})})}function D(e,n,r,i){return new hr(function(o){var s=0;return e.subscribe(function(u){var c;try{c=n.call(r,u,s,e)}catch(a){return o.onError(a),t}c?(o.onNext(i?s:u),o.onCompleted()):s++},o.onError.bind(o),function(){o.onNext(i?-1:t),o.onCompleted()})})}function S(t){var e=function(){this.cancelBubble=!0},n=function(){if(this.bubbledKeyCode=this.keyCode,this.ctrlKey)try{this.keyCode=0}catch(t){}this.defaultPrevented=!0,this.returnValue=!1,this.modified=!0};if(t||(t=X.event),!t.target)switch(t.target=t.target||t.srcElement,"mouseover"==t.type&&(t.relatedTarget=t.fromElement),"mouseout"==t.type&&(t.relatedTarget=t.toElement),t.stopPropagation||(t.stopPropagation=e,t.preventDefault=n),t.type){case"keypress":var r="charCode"in t?t.charCode:t.keyCode;10==r?(r=0,t.keyCode=13):13==r||27==r?r=0:3==r&&(r=99),t.charCode=r,t.keyChar=t.charCode?String.fromCharCode(t.charCode):""}return t}function N(t,e,n){if(t.addListener)return t.addListener(e,n),Je(function(){t.removeListener(e,n)});if(t.addEventListener)return t.addEventListener(e,n,!1),Je(function(){t.removeEventListener(e,n,!1)});if(t.attachEvent){var r=function(t){n(S(t))};return t.attachEvent("on"+e,r),Je(function(){t.detachEvent("on"+e,r)})}return t["on"+e]=n,Je(function(){t["on"+e]=null})}function A(t,e,n){var r=new Qe;if("function"==typeof t.item&&"number"==typeof t.length)for(var i=0,o=t.length;o>i;i++)r.add(A(t.item(i),e,n));else t&&r.add(N(t,e,n));return r}function _(e,n,r){return new hr(function(i){function o(e,n){h[n]=e;var o;if(u[n]=!0,c||(c=u.every(re))){try{o=r.apply(null,h)}catch(s){return i.onError(s),t}i.onNext(o)}else a&&i.onCompleted()}var s=2,u=[!1,!1],c=!1,a=!1,h=Array(s);return new Qe(e.subscribe(function(t){o(t,0)},i.onError.bind(i),function(){a=!0,i.onCompleted()}),n.subscribe(function(t){o(t,1)},i.onError.bind(i)))})}function O(t){if(false&t)return 2===t;for(var e=Math.sqrt(t),n=3;e>=n;){if(0===t%n)return!1;n+=2}return!0}function W(t){var e,n,r;for(e=0;Yn.length>e;++e)if(n=Yn[e],n>=t)return n;for(r=1|t;Yn[Yn.length-1]>r;){if(O(r))return r;r+=2}return t}function j(t){var e=757602046;if(!t.length)return e;for(var n=0,r=t.length;r>n;n++){var i=t.charCodeAt(n);e=(e<<5)-e+i,e&=e}return e}function k(t){var e=668265261;return t=61^t^t>>>16,t+=t<<3,t^=t>>>4,t*=e,t^=t>>>15}function R(){return{key:null,value:null,next:0,hashCode:0}}function q(t,e){return t.groupJoin(this,e,function(){return jn()},function(t,e){return e})}function P(t){var e=this;return new hr(function(n){var r=new pr,i=new Qe,o=new tn(i);return n.onNext(Me(r,o)),i.add(e.subscribe(function(t){r.onNext(t)},function(t){r.onError(t),n.onError(t)},function(){r.onCompleted(),n.onCompleted()})),i.add(t.subscribe(function(){r.onCompleted(),r=new pr,n.onNext(Me(r,o))},function(t){r.onError(t),n.onError(t)},function(){r.onCompleted(),n.onCompleted()})),o})}function T(e){var n=this;return new hr(function(r){var i,o=new Ye,s=new Qe(o),u=new tn(s),c=new pr;return r.onNext(Me(c,u)),s.add(n.subscribe(function(t){c.onNext(t)},function(t){c.onError(t),r.onError(t)},function(){c.onCompleted(),r.onCompleted()})),i=function(){var n,s;try{s=e()}catch(a){return r.onError(a),t}n=new Ge,o.setDisposable(n),n.setDisposable(s.take(1).subscribe(ne,function(t){c.onError(t),r.onError(t)},function(){c.onCompleted(),c=new pr,r.onNext(Me(c,u)),i()}))},i(),u})}function V(e,n){return new mn(function(){return new bn(function(){return e()?{done:!1,value:n}:{done:!0,value:t}})})}function z(t){this.patterns=t}function L(t,e){this.expression=t,this.selector=e}function M(t,e,n){var r=t.get(e);if(!r){var i=new ur(e,n);return t.set(e,i),i}return r}function I(t,e,n){var r,i;for(this.joinObserverArray=t,this.onNext=e,this.onCompleted=n,this.joinObservers=new sr,r=0;this.joinObserverArray.length>r;r++)i=this.joinObserverArray[r],this.joinObservers.set(i,i)}function F(t,e){return new hr(function(n){return e.scheduleWithAbsolute(t,function(){n.onNext(0),n.onCompleted()})})}function B(t,e,n){var r=on(e);return new hr(function(e){var i=0,o=t;return n.scheduleRecursiveWithAbsolute(o,function(t){var s;r>0&&(s=n.now(),o+=r,s>=o&&(o=s+r)),e.onNext(i++),t(o)})})}function H(t,e){var n=on(t);return new hr(function(t){return e.scheduleWithRelative(n,function(){t.onNext(0),t.onCompleted()})})}function U(t,e,n){return t===e?new hr(function(t){return n.schedulePeriodicWithState(0,e,function(e){return t.onNext(e),e+1})}):Wn(function(){return B(n.now()+t,e,n)})}function Q(t,e){var n=this;return new hr(function(r){var i,o=!1,s=new Ye,u=null,c=[],a=!1;return i=n.materialize().timestamp(e).subscribe(function(n){var i,h;"E"===n.value.kind?(c=[],c.push(n),u=n.value.exception,h=!a):(c.push({value:n.value,timestamp:n.timestamp+t}),h=!o,o=!0),h&&(null!==u?r.onError(u):(i=new Ge,s.setDisposable(i),i.setDisposable(e.scheduleRecursiveWithRelative(t,function(t){var n,i,s,h;if(null===u){a=!0;do s=null,c.length>0&&0>=c[0].timestamp-e.now()&&(s=c.shift().value),null!==s&&s.accept(r);while(null!==s);h=!1,i=0,c.length>0?(h=!0,i=Math.max(0,c[0].timestamp-e.now())):o=!1,n=u,a=!1,null!==n?r.onError(n):h&&t(i)}}))))}),new Qe(i,s)})}function $(t,e){var n=this;return Wn(function(){var r=t-e.now();return Q.call(n,r,e)})}function K(t,e){return new hr(function(n){function r(){s&&(s=!1,n.onNext(o)),i&&n.onCompleted()}var i,o,s;return new Qe(t.subscribe(function(t){s=!0,o=t},n.onError.bind(n),function(){i=!0}),e.subscribe(r,n.onError.bind(n),r))})}var J={"boolean":!1,"function":!0,object:!0,number:!1,string:!1,undefined:!1},X=J[typeof window]&&window||this,Z=J[typeof exports]&&exports&&!exports.nodeType&&exports,G=J[typeof module]&&module&&!module.nodeType&&module,Y=G&&G.exports===Z&&Z,te=J[typeof global]&&global;!te||te.global!==te&&te.window!==te||(X=te);var ee={internals:{},config:{Promise:X.Promise},helpers:{}},ne=ee.helpers.noop=function(){},re=ee.helpers.identity=function(t){return t},ie=(ee.helpers.pluck=function(t){return function(e){return e[t]}},ee.helpers.just=function(t){return function(){return t}},ee.helpers.defaultNow=function(){return Date.now?Date.now:function(){return+new Date}}()),oe=ee.helpers.defaultComparer=function(t,e){return Te(t,e)},se=ee.helpers.defaultSubComparer=function(t,e){return t>e?1:e>t?-1:0},ue=ee.helpers.defaultKeySerializer=function(t){return""+t},ce=ee.helpers.defaultError=function(t){throw t},ae=ee.helpers.isPromise=function(t){return!!t&&"function"==typeof t.then&&t.then!==ee.Observable.prototype.then};ee.helpers.asArray=function(){return Array.prototype.slice.call(arguments)},ee.helpers.not=function(t){return!t};var he="Sequence contains no elements.",le="Argument out of range",fe="Object has been disposed",pe="object"==typeof Symbol&&Symbol.iterator||"_es6shim_iterator_";X.Set&&"function"==typeof(new X.Set)["@@iterator"]&&(pe="@@iterator");var de,ve={done:!0,value:t},be="[object Arguments]",me="[object Array]",ye="[object Boolean]",we="[object Date]",ge="[object Error]",Ee="[object Function]",xe="[object Number]",Ce="[object Object]",De="[object RegExp]",Se="[object String]",Ne=Object.prototype.toString,Ae=Object.prototype.hasOwnProperty,_e=Ne.call(arguments)==be,Oe=Error.prototype,We=Object.prototype,je=We.propertyIsEnumerable;try{de=!(Ne.call(document)==Ce&&!({toString:0}+""))}catch(ke){de=!0}var Re=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],qe={};qe[me]=qe[we]=qe[xe]={constructor:!0,toLocaleString:!0,toString:!0,valueOf:!0},qe[ye]=qe[Se]={constructor:!0,toString:!0,valueOf:!0},qe[ge]=qe[Ee]=qe[De]={constructor:!0,toString:!0},qe[Ce]={constructor:!0};var Pe={};(function(){var t=function(){this.x=1},e=[];t.prototype={valueOf:1,y:1};for(var n in new t)e.push(n);for(n in arguments);Pe.enumErrorProps=je.call(Oe,"message")||je.call(Oe,"name"),Pe.enumPrototypes=je.call(t,"prototype"),Pe.nonEnumArgs=0!=n,Pe.nonEnumShadows=!/valueOf/.test(e)})(1),_e||(u=function(t){return t&&"object"==typeof t?Ae.call(t,"callee"):!1}),c(/x/)&&(c=function(t){return"function"==typeof t&&Ne.call(t)==Ee});var Te=ee.internals.isEqual=function(t,e){return a(t,e,[],[])},Ve=Array.prototype.slice;({}).hasOwnProperty;var ze=this.inherits=ee.internals.inherits=function(t,e){function n(){this.constructor=t}n.prototype=e.prototype,t.prototype=new n},Le=ee.internals.addProperties=function(t){for(var e=Ve.call(arguments,1),n=0,r=e.length;r>n;n++){var i=e[n];for(var o in i)t[o]=i[o]}},Me=ee.internals.addRef=function(t,e){return new hr(function(n){return new Qe(e.getDisposable(),t.subscribe(n))})};Function.prototype.bind||(Function.prototype.bind=function(t){var e=this,n=Ve.call(arguments,1),r=function(){function i(){}if(this instanceof r){i.prototype=e.prototype;var o=new i,s=e.apply(o,n.concat(Ve.call(arguments)));return Object(s)===s?s:o}return e.apply(t,n.concat(Ve.call(arguments)))};return r});var Ie=Object("a"),Fe="a"!=Ie[0]||!(0 in Ie);Array.prototype.every||(Array.prototype.every=function(t){var e=Object(this),n=Fe&&{}.toString.call(this)==Se?this.split(""):e,r=n.length>>>0,i=arguments[1];if({}.toString.call(t)!=Ee)throw new TypeError(t+" is not a function");for(var o=0;r>o;o++)if(o in n&&!t.call(i,n[o],o,e))return!1;return!0}),Array.prototype.map||(Array.prototype.map=function(t){var e=Object(this),n=Fe&&{}.toString.call(this)==Se?this.split(""):e,r=n.length>>>0,i=Array(r),o=arguments[1];if({}.toString.call(t)!=Ee)throw new TypeError(t+" is not a function");for(var s=0;r>s;s++)s in n&&(i[s]=t.call(o,n[s],s,e));return i}),Array.prototype.filter||(Array.prototype.filter=function(t){for(var e,n=[],r=Object(this),i=0,o=r.length>>>0;o>i;i++)e=r[i],i in r&&t.call(arguments[1],e,i,r)&&n.push(e);return n}),Array.isArray||(Array.isArray=function(t){return Object.prototype.toString.call(t)==me}),Array.prototype.indexOf||(Array.prototype.indexOf=function(t){var e=Object(this),n=e.length>>>0;if(0===n)return-1;var r=0;if(arguments.length>1&&(r=Number(arguments[1]),r!==r?r=0:0!==r&&1/0!=r&&r!==-1/0&&(r=(r>0||-1)*Math.floor(Math.abs(r)))),r>=n)return-1;for(var i=r>=0?r:Math.max(n-Math.abs(r),0);n>i;i++)if(i in e&&e[i]===t)return i;return-1});var Be=function(t,e){this.id=t,this.value=e};Be.prototype.compareTo=function(t){var e=this.value.compareTo(t.value);return 0===e&&(e=this.id-t.id),e};var He=ee.internals.PriorityQueue=function(t){this.items=Array(t),this.length=0},Ue=He.prototype;Ue.isHigherPriority=function(t,e){return 0>this.items[t].compareTo(this.items[e])},Ue.percolate=function(t){if(!(t>=this.length||0>t)){var e=t-1>>1;if(!(0>e||e===t)&&this.isHigherPriority(t,e)){var n=this.items[t];this.items[t]=this.items[e],this.items[e]=n,this.percolate(e)}}},Ue.heapify=function(e){if(e===t&&(e=0),!(e>=this.length||0>e)){var n=2*e+1,r=2*e+2,i=e;if(this.length>n&&this.isHigherPriority(n,i)&&(i=n),this.length>r&&this.isHigherPriority(r,i)&&(i=r),i!==e){var o=this.items[e];this.items[e]=this.items[i],this.items[i]=o,this.heapify(i)}}},Ue.peek=function(){return this.items[0].value},Ue.removeAt=function(t){this.items[t]=this.items[--this.length],delete this.items[this.length],this.heapify()},Ue.dequeue=function(){var t=this.peek();return this.removeAt(0),t},Ue.enqueue=function(t){var e=this.length++;this.items[e]=new Be(He.count++,t),this.percolate(e)},Ue.remove=function(t){for(var e=0;this.length>e;e++)if(this.items[e].value===t)return this.removeAt(e),!0;return!1},He.count=0;var Qe=ee.CompositeDisposable=function(){this.disposables=h(arguments,0),this.isDisposed=!1,this.length=this.disposables.length},$e=Qe.prototype;$e.add=function(t){this.isDisposed?t.dispose():(this.disposables.push(t),this.length++)},$e.remove=function(t){var e=!1;if(!this.isDisposed){var n=this.disposables.indexOf(t);-1!==n&&(e=!0,this.disposables.splice(n,1),this.length--,t.dispose())}return e},$e.dispose=function(){if(!this.isDisposed){this.isDisposed=!0;var t=this.disposables.slice(0);this.disposables=[],this.length=0;for(var e=0,n=t.length;n>e;e++)t[e].dispose()}},$e.clear=function(){var t=this.disposables.slice(0);this.disposables=[],this.length=0;for(var e=0,n=t.length;n>e;e++)t[e].dispose()},$e.contains=function(t){return-1!==this.disposables.indexOf(t)},$e.toArray=function(){return this.disposables.slice(0)};var Ke=ee.Disposable=function(t){this.isDisposed=!1,this.action=t||ne};Ke.prototype.dispose=function(){this.isDisposed||(this.action(),this.isDisposed=!0)};var Je=Ke.create=function(t){return new Ke(t)},Xe=Ke.empty={dispose:ne},Ze=function(){function t(t){this.isSingle=t,this.isDisposed=!1,this.current=null}var e=t.prototype;return e.getDisposable=function(){return this.current},e.setDisposable=function(t){if(this.current&&this.isSingle)throw Error("Disposable has already been assigned");var e,n=this.isDisposed;n||(e=this.current,this.current=t),e&&e.dispose(),n&&t&&t.dispose()},e.dispose=function(){var t;this.isDisposed||(this.isDisposed=!0,t=this.current,this.current=null),t&&t.dispose()},t}(),Ge=ee.SingleAssignmentDisposable=function(t){function e(){t.call(this,!0)}return ze(e,t),e}(Ze),Ye=ee.SerialDisposable=function(t){function e(){t.call(this,!1)}return ze(e,t),e}(Ze),tn=ee.RefCountDisposable=function(){function t(t){this.disposable=t,this.disposable.count++,this.isInnerDisposed=!1}function e(t){this.underlyingDisposable=t,this.isDisposed=!1,this.isPrimaryDisposed=!1,this.count=0}return t.prototype.dispose=function(){this.disposable.isDisposed||this.isInnerDisposed||(this.isInnerDisposed=!0,this.disposable.count--,0===this.disposable.count&&this.disposable.isPrimaryDisposed&&(this.disposable.isDisposed=!0,this.disposable.underlyingDisposable.dispose()))},e.prototype.dispose=function(){this.isDisposed||this.isPrimaryDisposed||(this.isPrimaryDisposed=!0,0===this.count&&(this.isDisposed=!0,this.underlyingDisposable.dispose()))},e.prototype.getDisposable=function(){return this.isDisposed?Xe:new t(this)},e}();f.prototype.dispose=function(){var t=this;this.scheduler.schedule(function(){t.isDisposed||(t.isDisposed=!0,t.disposable.dispose())})};var en=ee.internals.ScheduledItem=function(t,e,n,r,i){this.scheduler=t,this.state=e,this.action=n,this.dueTime=r,this.comparer=i||se,this.disposable=new Ge};en.prototype.invoke=function(){this.disposable.setDisposable(this.invokeCore())},en.prototype.compareTo=function(t){return this.comparer(this.dueTime,t.dueTime)},en.prototype.isCancelled=function(){return this.disposable.isDisposed},en.prototype.invokeCore=function(){return this.action(this.scheduler,this.state)};var nn,rn=ee.Scheduler=function(){function t(t,e,n,r){this.now=t,this._schedule=e,this._scheduleRelative=n,this._scheduleAbsolute=r}function e(t,e){var n=e.first,r=e.second,i=new Qe,o=function(e){r(e,function(e){var n=!1,r=!1,s=t.scheduleWithState(e,function(t,e){return n?i.remove(s):r=!0,o(e),Xe});r||(i.add(s),n=!0)})};return o(n),i}function n(t,e,n){var r=e.first,i=e.second,o=new Qe,s=function(e){i(e,function(e,r){var i=!1,u=!1,c=t[n].call(t,e,r,function(t,e){return i?o.remove(c):u=!0,s(e),Xe});u||(o.add(c),i=!0)})};return s(r),o}function r(t,e){return e(),Xe}var i=t.prototype;return i.catchException=i["catch"]=function(t){return new ln(this,t)},i.schedulePeriodic=function(t,e){return this.schedulePeriodicWithState(null,t,function(){e()})},i.schedulePeriodicWithState=function(t,e,n){var r=t,i=setInterval(function(){r=n(r)},e);return Je(function(){clearInterval(i)})},i.schedule=function(t){return this._schedule(t,r)},i.scheduleWithState=function(t,e){return this._schedule(t,e)},i.scheduleWithRelative=function(t,e){return this._scheduleRelative(e,t,r)},i.scheduleWithRelativeAndState=function(t,e,n){return this._scheduleRelative(t,e,n)},i.scheduleWithAbsolute=function(t,e){return this._scheduleAbsolute(e,t,r)},i.scheduleWithAbsoluteAndState=function(t,e,n){return this._scheduleAbsolute(t,e,n)},i.scheduleRecursive=function(t){return this.scheduleRecursiveWithState(t,function(t,e){t(function(){e(t)})})},i.scheduleRecursiveWithState=function(t,n){return this.scheduleWithState({first:t,second:n},function(t,n){return e(t,n)})},i.scheduleRecursiveWithRelative=function(t,e){return this.scheduleRecursiveWithRelativeAndState(e,t,function(t,e){t(function(n){e(t,n)})})},i.scheduleRecursiveWithRelativeAndState=function(t,e,r){return this._scheduleRelative({first:t,second:r},e,function(t,e){return n(t,e,"scheduleWithRelativeAndState")})},i.scheduleRecursiveWithAbsolute=function(t,e){return this.scheduleRecursiveWithAbsoluteAndState(e,t,function(t,e){t(function(n){e(t,n)})})},i.scheduleRecursiveWithAbsoluteAndState=function(t,e,r){return this._scheduleAbsolute({first:t,second:r},e,function(t,e){return n(t,e,"scheduleWithAbsoluteAndState")})},t.now=ie,t.normalize=function(t){return 0>t&&(t=0),t},t}(),on=rn.normalize,sn=ee.internals.SchedulePeriodicRecursive=function(){function t(t,e){e(0,this._period);try{this._state=this._action(this._state)}catch(n){throw this._cancel.dispose(),n}}function e(t,e,n,r){this._scheduler=t,this._state=e,this._period=n,this._action=r}return e.prototype.start=function(){var e=new Ge;return this._cancel=e,e.setDisposable(this._scheduler.scheduleRecursiveWithRelativeAndState(0,this._period,t.bind(this))),e},e}(),un=rn.immediate=function(){function t(t,e){return e(this,t)}function e(t,e,n){for(var r=on(r);r-this.now()>0;);return n(this,t)}function n(t,e,n){return this.scheduleWithRelativeAndState(t,e-this.now(),n)}return new rn(ie,t,e,n)}(),cn=rn.currentThread=function(){function t(t){for(var e;t.length>0;)if(e=t.dequeue(),!e.isCancelled()){for(;e.dueTime-rn.now()>0;);e.isCancelled()||e.invoke()}}function e(t,e){return this.scheduleWithRelativeAndState(t,0,e)}function n(e,n,r){var o=this.now()+rn.normalize(n),s=new en(this,e,r,o);if(i)i.enqueue(s);else{i=new He(4),i.enqueue(s);try{t(i)}catch(u){throw u}finally{i=null}}return s.disposable}function r(t,e,n){return this.scheduleWithRelativeAndState(t,e-this.now(),n)}var i,o=new rn(ie,e,n,r);return o.scheduleRequired=function(){return null===i},o.ensureTrampoline=function(t){return null===i?this.schedule(t):t()},o}(),an=ne;(function(){function t(){if(!X.postMessage||X.importScripts)return!1;var t=!1,e=X.onmessage;return X.onmessage=function(){t=!0},X.postMessage("","*"),X.onmessage=e,t}function e(t){if("string"==typeof t.data&&t.data.substring(0,o.length)===o){var e=t.data.substring(o.length),n=s[e];n(),delete s[e]}}var n=RegExp("^"+(Ne+"").replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/toString| for [^\]]+/g,".*?")+"$"),r="function"==typeof(r=te&&Y&&te.setImmediate)&&!n.test(r)&&r,i="function"==typeof(i=te&&Y&&te.clearImmediate)&&!n.test(i)&&i;if("undefined"!=typeof process&&"[object process]"==={}.toString.call(process))nn=process.nextTick;else if("function"==typeof r)nn=r,an=i;else if(t()){var o="ms.rx.schedule"+Math.random(),s={},u=0;X.addEventListener?X.addEventListener("message",e,!1):X.attachEvent("onmessage",e,!1),nn=function(t){var e=u++;s[e]=t,X.postMessage(o+e,"*")}}else if(X.MessageChannel){var c=new X.MessageChannel,a={},h=0;c.port1.onmessage=function(t){var e=t.data,n=a[e];n(),delete a[e]},nn=function(t){var e=h++;a[e]=t,c.port2.postMessage(e)}}else"document"in X&&"onreadystatechange"in X.document.createElement("script")?nn=function(t){var e=X.document.createElement("script");e.onreadystatechange=function(){t(),e.onreadystatechange=null,e.parentNode.removeChild(e),e=null},X.document.documentElement.appendChild(e)}:(nn=function(t){return setTimeout(t,0)},an=clearTimeout)})();var hn=rn.timeout=function(){function t(t,e){var n=this,r=new Ge,i=nn(function(){r.isDisposed||r.setDisposable(e(n,t))});return new Qe(r,Je(function(){an(i)}))}function e(t,e,n){var r=this,i=rn.normalize(e);if(0===i)return r.scheduleWithState(t,n);var o=new Ge,s=setTimeout(function(){o.isDisposed||o.setDisposable(n(r,t))},i);return new Qe(o,Je(function(){clearTimeout(s)}))}function n(t,e,n){return this.scheduleWithRelativeAndState(t,e-this.now(),n)}return new rn(ie,t,e,n)}(),ln=function(t){function e(){return this._scheduler.now()}function n(t,e){return this._scheduler.scheduleWithState(t,this._wrap(e))}function r(t,e,n){return this._scheduler.scheduleWithRelativeAndState(t,e,this._wrap(n))}function i(t,e,n){return this._scheduler.scheduleWithAbsoluteAndState(t,e,this._wrap(n))}function o(o,s){this._scheduler=o,this._handler=s,this._recursiveOriginal=null,this._recursiveWrapper=null,t.call(this,e,n,r,i)}return ze(o,t),o.prototype._clone=function(t){return new o(t,this._handler)},o.prototype._wrap=function(t){var e=this;return function(n,r){try{return t(e._getRecursiveWrapper(n),r)}catch(i){if(!e._handler(i))throw i;return Xe}}},o.prototype._getRecursiveWrapper=function(t){if(this._recursiveOriginal!==t){this._recursiveOriginal=t;var e=this._clone(t);e._recursiveOriginal=t,e._recursiveWrapper=e,this._recursiveWrapper=e}return this._recursiveWrapper},o.prototype.schedulePeriodicWithState=function(t,e,n){var r=this,i=!1,o=new Ge;return o.setDisposable(this._scheduler.schedulePeriodicWithState(t,e,function(t){if(i)return null;try{return n(t)}catch(e){if(i=!0,!r._handler(e))throw e;return o.dispose(),null}})),o},o}(rn),fn=ee.Notification=function(){function t(t,e){this.hasValue=null==e?!1:e,this.kind=t}var e=t.prototype;return e.accept=function(t,e,n){return 1===arguments.length&&"object"==typeof t?this._acceptObservable(t):this._accept(t,e,n)},e.toObservable=function(t){var e=this;return t||(t=un),new hr(function(n){return t.schedule(function(){e._acceptObservable(n),"N"===e.kind&&n.onCompleted()})})},t}(),pn=fn.createOnNext=function(){function t(t){return t(this.value)}function e(t){return t.onNext(this.value)}function n(){return"OnNext("+this.value+")"}return function(r){var i=new fn("N",!0);return i.value=r,i._accept=t,i._acceptObservable=e,i.toString=n,i}}(),dn=fn.createOnError=function(){function t(t,e){return e(this.exception)}function e(t){return t.onError(this.exception)}function n(){return"OnError("+this.exception+")"}return function(r){var i=new fn("E");return i.exception=r,i._accept=t,i._acceptObservable=e,i.toString=n,i}}(),vn=fn.createOnCompleted=function(){function t(t,e,n){return n()}function e(t){return t.onCompleted()}function n(){return"OnCompleted()"}return function(){var r=new fn("C");return r._accept=t,r._acceptObservable=e,r.toString=n,r}}(),bn=ee.internals.Enumerator=function(t){this._next=t};bn.prototype.next=function(){return this._next()},bn.prototype[pe]=function(){return this};var mn=ee.internals.Enumerable=function(t){this._iterator=t};mn.prototype[pe]=function(){return this._iterator()},mn.prototype.concat=function(){var e=this;return new hr(function(n){var r;try{r=e[pe]()}catch(i){return n.onError(),t}var o,s=new Ye,u=un.scheduleRecursive(function(e){var i;if(!o){try{i=r.next()}catch(u){return n.onError(u),t}if(i.done)return n.onCompleted(),t;var c=i.value;ae(c)&&(c=On(c));var a=new Ge;s.setDisposable(a),a.setDisposable(c.subscribe(n.onNext.bind(n),n.onError.bind(n),function(){e()}))}});return new Qe(s,u,Je(function(){o=!0}))})},mn.prototype.catchException=function(){var e=this;return new hr(function(n){var r;try{r=e[pe]()}catch(i){return n.onError(),t}var o,s,u=new Ye,c=un.scheduleRecursive(function(e){if(!o){var i;try{i=r.next()}catch(c){return n.onError(c),t}if(i.done)return s?n.onError(s):n.onCompleted(),t;var a=i.value;ae(a)&&(a=On(a));var h=new Ge;u.setDisposable(h),h.setDisposable(a.subscribe(n.onNext.bind(n),function(t){s=t,e()},n.onCompleted.bind(n)))}});return new Qe(u,c,Je(function(){o=!0}))})};var yn=mn.repeat=function(t,e){return null==e&&(e=-1),new mn(function(){var n=e;return new bn(function(){return 0===n?ve:(n>0&&n--,{done:!1,value:t})})})},wn=mn.forEach=function(t,e,n){return e||(e=re),new mn(function(){var r=-1;return new bn(function(){return++r0&&(e=!this.isAcquired,this.isAcquired=!0),e&&this.disposable.setDisposable(this.scheduler.scheduleRecursive(function(e){var r;if(!(n.queue.length>0))return n.isAcquired=!1,t;r=n.queue.shift();try{r()}catch(i){throw n.queue=[],n.hasFaulted=!0,i}e()}))},n.prototype.dispose=function(){e.prototype.dispose.call(this),this.disposable.dispose()},n}(Cn),An=function(t){function e(){t.apply(this,arguments)}return ze(e,t),e.prototype.next=function(e){t.prototype.next.call(this,e),this.ensureActive()},e.prototype.error=function(e){t.prototype.error.call(this,e),this.ensureActive()},e.prototype.completed=function(){t.prototype.completed.call(this),this.ensureActive()},e}(Nn),_n=ee.Observable=function(){function t(t){this._subscribe=t}return xn=t.prototype,xn.subscribe=xn.forEach=function(t,e,n){var r="object"==typeof t?t:En(t,e,n);return this._subscribe(r)},t}();xn.observeOn=function(t){var e=this;return new hr(function(n){return e.subscribe(new An(t,n))})},xn.subscribeOn=function(t){var e=this;return new hr(function(n){var r=new Ge,i=new Ye;return i.setDisposable(r),r.setDisposable(t.schedule(function(){i.setDisposable(new f(t,e.subscribe(n)))})),i})};var On=_n.fromPromise=function(t){return new hr(function(e){return t.then(function(t){e.onNext(t),e.onCompleted()},function(t){e.onError(t)}),function(){t&&t.abort&&t.abort()}})};xn.toPromise=function(t){if(t||(t=ee.config.Promise),!t)throw Error("Promise type not provided nor in Rx.config.Promise"); +var e=this;return new t(function(t,n){var r,i=!1;e.subscribe(function(t){r=t,i=!0},function(t){n(t)},function(){i&&t(r)})})},xn.toArray=function(){var t=this;return new hr(function(e){var n=[];return t.subscribe(n.push.bind(n),e.onError.bind(e),function(){e.onNext(n),e.onCompleted()})})},_n.create=_n.createWithDisposable=function(t){return new hr(t)};var Wn=_n.defer=function(t){return new hr(function(e){var n;try{n=t()}catch(r){return Pn(r).subscribe(e)}return ae(n)&&(n=On(n)),n.subscribe(e)})},jn=_n.empty=function(t){return t||(t=un),new hr(function(e){return t.schedule(function(){e.onCompleted()})})},kn=_n.fromArray=function(t,e){return e||(e=cn),new hr(function(n){var r=0,i=t.length;return e.scheduleRecursive(function(e){i>r?(n.onNext(t[r++]),e()):n.onCompleted()})})};_n.fromIterable=function(e,n){return n||(n=cn),new hr(function(r){var i;try{i=e[pe]()}catch(o){return r.onError(o),t}return n.scheduleRecursive(function(e){var n;try{n=i.next()}catch(o){return r.onError(o),t}n.done?r.onCompleted():(r.onNext(n.value),e())})})},_n.generate=function(e,n,r,i,o){return o||(o=cn),new hr(function(s){var u=!0,c=e;return o.scheduleRecursive(function(e){var o,a;try{u?u=!1:c=r(c),o=n(c),o&&(a=i(c))}catch(h){return s.onError(h),t}o?(s.onNext(a),e()):s.onCompleted()})})},_n.of=function(){for(var t=arguments.length,e=Array(t),n=0;t>n;n++)e[n]=arguments[n];return kn(e)},_n.ofWithScheduler=function(t){for(var e=arguments.length-1,n=Array(e),r=0;e>r;r++)n[r]=arguments[r+1];return kn(n,t)};var Rn=_n.never=function(){return new hr(function(){return Xe})};_n.range=function(t,e,n){return n||(n=cn),new hr(function(r){return n.scheduleRecursiveWithState(0,function(n,i){e>n?(r.onNext(t+n),i(n+1)):r.onCompleted()})})},_n.repeat=function(t,e,n){return n||(n=cn),null==e&&(e=-1),qn(t,n).repeat(e)};var qn=_n["return"]=_n.returnValue=_n.just=function(t,e){return e||(e=un),new hr(function(n){return e.schedule(function(){n.onNext(t),n.onCompleted()})})},Pn=_n["throw"]=_n.throwException=function(t,e){return e||(e=un),new hr(function(n){return e.schedule(function(){n.onError(t)})})};_n.using=function(t,e){return new hr(function(n){var r,i,o=Xe;try{r=t(),r&&(o=r),i=e(r)}catch(s){return new Qe(Pn(s).subscribe(n),o)}return new Qe(i.subscribe(n),o)})},xn.amb=function(t){var e=this;return new hr(function(n){function r(){o||(o=s,a.dispose())}function i(){o||(o=u,c.dispose())}var o,s="L",u="R",c=new Ge,a=new Ge;return ae(t)&&(t=On(t)),c.setDisposable(e.subscribe(function(t){r(),o===s&&n.onNext(t)},function(t){r(),o===s&&n.onError(t)},function(){r(),o===s&&n.onCompleted()})),a.setDisposable(t.subscribe(function(t){i(),o===u&&n.onNext(t)},function(t){i(),o===u&&n.onError(t)},function(){i(),o===u&&n.onCompleted()})),new Qe(c,a)})},_n.amb=function(){function t(t,e){return t.amb(e)}for(var e=Rn(),n=h(arguments,0),r=0,i=n.length;i>r;r++)e=t(e,n[r]);return e},xn["catch"]=xn.catchException=function(t){return"function"==typeof t?p(this,t):Tn([this,t])};var Tn=_n.catchException=_n["catch"]=function(){var t=h(arguments,0);return wn(t).catchException()};xn.combineLatest=function(){var t=Ve.call(arguments);return Array.isArray(t[0])?t[0].unshift(this):t.unshift(this),Vn.apply(this,t)};var Vn=_n.combineLatest=function(){var e=Ve.call(arguments),n=e.pop();return Array.isArray(e[0])&&(e=e[0]),new hr(function(r){function i(e){var i;if(c[e]=!0,a||(a=c.every(re))){try{i=n.apply(null,f)}catch(o){return r.onError(o),t}r.onNext(i)}else h.filter(function(t,n){return n!==e}).every(re)&&r.onCompleted()}function o(t){h[t]=!0,h.every(re)&&r.onCompleted()}for(var s=function(){return!1},u=e.length,c=l(u,s),a=!1,h=l(u,s),f=Array(u),p=Array(u),d=0;u>d;d++)(function(t){var n=e[t],s=new Ge;ae(n)&&(n=On(n)),s.setDisposable(n.subscribe(function(e){f[t]=e,i(t)},r.onError.bind(r),function(){o(t)})),p[t]=s})(d);return new Qe(p)})};xn.concat=function(){var t=Ve.call(arguments,0);return t.unshift(this),zn.apply(this,t)};var zn=_n.concat=function(){var t=h(arguments,0);return wn(t).concat()};xn.concatObservable=xn.concatAll=function(){return this.merge(1)},xn.merge=function(t){if("number"!=typeof t)return Ln(this,t);var e=this;return new hr(function(n){var r=0,i=new Qe,o=!1,s=[],u=function(t){var e=new Ge;i.add(e),ae(t)&&(t=On(t)),e.setDisposable(t.subscribe(n.onNext.bind(n),n.onError.bind(n),function(){var t;i.remove(e),s.length>0?(t=s.shift(),u(t)):(r--,o&&0===r&&n.onCompleted())}))};return i.add(e.subscribe(function(e){t>r?(r++,u(e)):s.push(e)},n.onError.bind(n),function(){o=!0,0===r&&n.onCompleted()})),i})};var Ln=_n.merge=function(){var t,e;return arguments[0]?arguments[0].now?(t=arguments[0],e=Ve.call(arguments,1)):(t=un,e=Ve.call(arguments,0)):(t=un,e=Ve.call(arguments,1)),Array.isArray(e[0])&&(e=e[0]),kn(e,t).mergeObservable()};xn.mergeObservable=xn.mergeAll=function(){var t=this;return new hr(function(e){var n=new Qe,r=!1,i=new Ge;return n.add(i),i.setDisposable(t.subscribe(function(t){var i=new Ge;n.add(i),ae(t)&&(t=On(t)),i.setDisposable(t.subscribe(function(t){e.onNext(t)},e.onError.bind(e),function(){n.remove(i),r&&1===n.length&&e.onCompleted()}))},e.onError.bind(e),function(){r=!0,1===n.length&&e.onCompleted()})),n})},xn.onErrorResumeNext=function(t){if(!t)throw Error("Second observable is required");return Mn([this,t])};var Mn=_n.onErrorResumeNext=function(){var t=h(arguments,0);return new hr(function(e){var n=0,r=new Ye,i=un.scheduleRecursive(function(i){var o,s;t.length>n?(o=t[n++],ae(o)&&(o=On(o)),s=new Ge,r.setDisposable(s),s.setDisposable(o.subscribe(e.onNext.bind(e),function(){i()},function(){i()}))):e.onCompleted()});return new Qe(r,i)})};xn.skipUntil=function(t){var e=this;return new hr(function(n){var r=!1,i=new Qe(e.subscribe(function(t){r&&n.onNext(t)},n.onError.bind(n),function(){r&&n.onCompleted()}));ae(t)&&(t=On(t));var o=new Ge;return i.add(o),o.setDisposable(t.subscribe(function(){r=!0,o.dispose()},n.onError.bind(n),function(){o.dispose()})),i})},xn["switch"]=xn.switchLatest=function(){var t=this;return new hr(function(e){var n=!1,r=new Ye,i=!1,o=0,s=t.subscribe(function(t){var s=new Ge,u=++o;n=!0,r.setDisposable(s),ae(t)&&(t=On(t)),s.setDisposable(t.subscribe(function(t){o===u&&e.onNext(t)},function(t){o===u&&e.onError(t)},function(){o===u&&(n=!1,i&&e.onCompleted())}))},e.onError.bind(e),function(){i=!0,n||e.onCompleted()});return new Qe(s,r)})},xn.takeUntil=function(t){var e=this;return new hr(function(n){return ae(t)&&(t=On(t)),new Qe(e.subscribe(n),t.subscribe(n.onCompleted.bind(n),n.onError.bind(n),ne))})},xn.zip=function(){if(Array.isArray(arguments[0]))return d.apply(this,arguments);var e=this,n=Ve.call(arguments),r=n.pop();return n.unshift(e),new hr(function(i){function o(n){var o,s;if(c.every(function(t){return t.length>0})){try{s=c.map(function(t){return t.shift()}),o=r.apply(e,s)}catch(u){return i.onError(u),t}i.onNext(o)}else a.filter(function(t,e){return e!==n}).every(re)&&i.onCompleted()}function s(t){a[t]=!0,a.every(function(t){return t})&&i.onCompleted()}for(var u=n.length,c=l(u,function(){return[]}),a=l(u,function(){return!1}),h=Array(u),f=0;u>f;f++)(function(t){var e=n[t],r=new Ge;ae(e)&&(e=On(e)),r.setDisposable(e.subscribe(function(e){c[t].push(e),o(t)},i.onError.bind(i),function(){s(t)})),h[t]=r})(f);return new Qe(h)})},_n.zip=function(){var t=Ve.call(arguments,0),e=t.shift();return e.zip.apply(e,t)},_n.zipArray=function(){var e=h(arguments,0);return new hr(function(n){function r(e){if(s.every(function(t){return t.length>0})){var r=s.map(function(t){return t.shift()});n.onNext(r)}else if(u.filter(function(t,n){return n!==e}).every(re))return n.onCompleted(),t}function i(e){return u[e]=!0,u.every(re)?(n.onCompleted(),t):t}for(var o=e.length,s=l(o,function(){return[]}),u=l(o,function(){return!1}),c=Array(o),a=0;o>a;a++)(function(t){c[t]=new Ge,c[t].setDisposable(e[t].subscribe(function(e){s[t].push(e),r(t)},n.onError.bind(n),function(){i(t)}))})(a);var h=new Qe(c);return h.add(Je(function(){for(var t=0,e=s.length;e>t;t++)s[t]=[]})),h})},xn.asObservable=function(){var t=this;return new hr(function(e){return t.subscribe(e)})},xn.bufferWithCount=function(t,e){return"number"!=typeof e&&(e=t),this.windowWithCount(t,e).selectMany(function(t){return t.toArray()}).where(function(t){return t.length>0})},xn.dematerialize=function(){var t=this;return new hr(function(e){return t.subscribe(function(t){return t.accept(e)},e.onError.bind(e),e.onCompleted.bind(e))})},xn.distinctUntilChanged=function(e,n){var r=this;return e||(e=re),n||(n=oe),new hr(function(i){var o,s=!1;return r.subscribe(function(r){var u,c=!1;try{u=e(r)}catch(a){return i.onError(a),t}if(s)try{c=n(o,u)}catch(a){return i.onError(a),t}s&&c||(s=!0,o=u,i.onNext(r))},i.onError.bind(i),i.onCompleted.bind(i))})},xn["do"]=xn.doAction=function(t,e,n){var r,i=this;return"function"==typeof t?r=t:(r=t.onNext.bind(t),e=t.onError.bind(t),n=t.onCompleted.bind(t)),new hr(function(t){return i.subscribe(function(e){try{r(e)}catch(n){t.onError(n)}t.onNext(e)},function(n){if(e){try{e(n)}catch(r){t.onError(r)}t.onError(n)}else t.onError(n)},function(){if(n){try{n()}catch(e){t.onError(e)}t.onCompleted()}else t.onCompleted()})})},xn["finally"]=xn.finallyAction=function(t){var e=this;return new hr(function(n){var r;try{r=e.subscribe(n)}catch(i){throw t(),i}return Je(function(){try{r.dispose()}catch(e){throw e}finally{t()}})})},xn.ignoreElements=function(){var t=this;return new hr(function(e){return t.subscribe(ne,e.onError.bind(e),e.onCompleted.bind(e))})},xn.materialize=function(){var t=this;return new hr(function(e){return t.subscribe(function(t){e.onNext(pn(t))},function(t){e.onNext(dn(t)),e.onCompleted()},function(){e.onNext(vn()),e.onCompleted()})})},xn.repeat=function(t){return yn(this,t).concat()},xn.retry=function(t){return yn(this,t).catchException()},xn.scan=function(){var e,n,r=!1,i=this;return 2===arguments.length?(r=!0,e=arguments[0],n=arguments[1]):n=arguments[0],new hr(function(o){var s,u,c;return i.subscribe(function(i){try{c||(c=!0),s?u=n(u,i):(u=r?n(e,i):i,s=!0)}catch(a){return o.onError(a),t}o.onNext(u)},o.onError.bind(o),function(){!c&&r&&o.onNext(e),o.onCompleted()})})},xn.skipLast=function(t){var e=this;return new hr(function(n){var r=[];return e.subscribe(function(e){r.push(e),r.length>t&&n.onNext(r.shift())},n.onError.bind(n),n.onCompleted.bind(n))})},xn.startWith=function(){var t,e,n=0;return arguments.length&&"now"in Object(arguments[0])?(e=arguments[0],n=1):e=un,t=Ve.call(arguments,n),wn([kn(t,e),this]).concat()},xn.takeLast=function(t,e){return this.takeLastBuffer(t).selectMany(function(t){return kn(t,e)})},xn.takeLastBuffer=function(t){var e=this;return new hr(function(n){var r=[];return e.subscribe(function(e){r.push(e),r.length>t&&r.shift()},n.onError.bind(n),function(){n.onNext(r),n.onCompleted()})})},xn.windowWithCount=function(t,e){var n=this;if(0>=t)throw Error(le);if(1===arguments.length&&(e=t),0>=e)throw Error(le);return new hr(function(r){var i=new Ge,o=new tn(i),s=0,u=[],c=function(){var t=new pr;u.push(t),r.onNext(Me(t,o))};return c(),i.setDisposable(n.subscribe(function(n){for(var r,i=0,o=u.length;o>i;i++)u[i].onNext(n);var a=s-t+1;a>=0&&0===a%e&&(r=u.shift(),r.onCompleted()),s++,0===s%e&&c()},function(t){for(;u.length>0;)u.shift().onError(t);r.onError(t)},function(){for(;u.length>0;)u.shift().onCompleted();r.onCompleted()})),o})},xn.selectConcat=xn.concatMap=function(t,e){return e?this.concatMap(function(n,r){var i=t(n,r),o=ae(i)?On(i):i;return o.map(function(t){return e(n,t,r)})}):"function"==typeof t?v.call(this,t):v.call(this,function(){return t})},xn.defaultIfEmpty=function(e){var n=this;return e===t&&(e=null),new hr(function(t){var r=!1;return n.subscribe(function(e){r=!0,t.onNext(e)},t.onError.bind(t),function(){r||t.onNext(e),t.onCompleted()})})},xn.distinct=function(e,n){var r=this;return e||(e=re),n||(n=ue),new hr(function(i){var o={};return r.subscribe(function(r){var s,u,c,a=!1;try{s=e(r),u=n(s)}catch(h){return i.onError(h),t}for(c in o)if(u===c){a=!0;break}a||(o[u]=null,i.onNext(r))},i.onError.bind(i),i.onCompleted.bind(i))})},xn.groupBy=function(t,e,n){return this.groupByUntil(t,e,function(){return Rn()},n)},xn.groupByUntil=function(e,n,r,i){var o=this;return n||(n=re),i||(i=ue),new hr(function(s){var u={},c=new Qe,a=new tn(c);return c.add(o.subscribe(function(o){var h,l,f,p,d,v,b,m,y,w;try{v=e(o),b=i(v)}catch(g){for(w in u)u[w].onError(g);return s.onError(g),t}p=!1;try{y=u[b],y||(y=new pr,u[b]=y,p=!0)}catch(g){for(w in u)u[w].onError(g);return s.onError(g),t}if(p){d=new fr(v,y,a),l=new fr(v,y);try{h=r(l)}catch(g){for(w in u)u[w].onError(g);return s.onError(g),t}s.onNext(d),m=new Ge,c.add(m);var E=function(){b in u&&(delete u[b],y.onCompleted()),c.remove(m)};m.setDisposable(h.take(1).subscribe(ne,function(t){for(w in u)u[w].onError(t);s.onError(t)},function(){E()}))}try{f=n(o)}catch(g){for(w in u)u[w].onError(g);return s.onError(g),t}y.onNext(f)},function(t){for(var e in u)u[e].onError(t);s.onError(t)},function(){for(var t in u)u[t].onCompleted();s.onCompleted()})),a})},xn.select=xn.map=function(e,n){var r=this;return new hr(function(i){var o=0;return r.subscribe(function(s){var u;try{u=e.call(n,s,o++,r)}catch(c){return i.onError(c),t}i.onNext(u)},i.onError.bind(i),i.onCompleted.bind(i))})},xn.pluck=function(t){return this.select(function(e){return e[t]})},xn.selectMany=xn.flatMap=function(t,e){return e?this.selectMany(function(n,r){var i=t(n,r),o=ae(i)?On(i):i;return o.select(function(t){return e(n,t,r)})}):"function"==typeof t?b.call(this,t):b.call(this,function(){return t})},xn.selectSwitch=xn.flatMapLatest=xn.switchMap=function(t,e){return this.select(t,e).switchLatest()},xn.skip=function(t){if(0>t)throw Error(le);var e=this;return new hr(function(n){var r=t;return e.subscribe(function(t){0>=r?n.onNext(t):r--},n.onError.bind(n),n.onCompleted.bind(n))})},xn.skipWhile=function(e,n){var r=this;return new hr(function(i){var o=0,s=!1;return r.subscribe(function(u){if(!s)try{s=!e.call(n,u,o++,r)}catch(c){return i.onError(c),t}s&&i.onNext(u)},i.onError.bind(i),i.onCompleted.bind(i))})},xn.take=function(t,e){if(0>t)throw Error(le);if(0===t)return jn(e);var n=this;return new hr(function(e){var r=t;return n.subscribe(function(t){r>0&&(r--,e.onNext(t),0===r&&e.onCompleted())},e.onError.bind(e),e.onCompleted.bind(e))})},xn.takeWhile=function(e,n){var r=this;return new hr(function(i){var o=0,s=!0;return r.subscribe(function(u){if(s){try{s=e.call(n,u,o++,r)}catch(c){return i.onError(c),t}s?i.onNext(u):i.onCompleted()}},i.onError.bind(i),i.onCompleted.bind(i))})},xn.where=xn.filter=function(e,n){var r=this;return new hr(function(i){var o=0;return r.subscribe(function(s){var u;try{u=e.call(n,s,o++,r)}catch(c){return i.onError(c),t}u&&i.onNext(s)},i.onError.bind(i),i.onCompleted.bind(i))})},xn.finalValue=function(){var t=this;return new hr(function(e){var n,r=!1;return t.subscribe(function(t){r=!0,n=t},e.onError.bind(e),function(){r?(e.onNext(n),e.onCompleted()):e.onError(Error(he))})})},xn.aggregate=function(){var t,e,n;return 2===arguments.length?(t=arguments[0],e=!0,n=arguments[1]):n=arguments[0],e?this.scan(t,n).startWith(t).finalValue():this.scan(n).finalValue()},xn.reduce=function(t){var e,n;return 2===arguments.length&&(n=!0,e=arguments[1]),n?this.scan(e,t).startWith(e).finalValue():this.scan(t).finalValue()},xn.some=xn.any=function(t,e){var n=this;return t?n.where(t,e).any():new hr(function(t){return n.subscribe(function(){t.onNext(!0),t.onCompleted()},t.onError.bind(t),function(){t.onNext(!1),t.onCompleted()})})},xn.isEmpty=function(){return this.any().select(function(t){return!t})},xn.every=xn.all=function(t,e){return this.where(function(e){return!t(e)},e).any().select(function(t){return!t})},xn.contains=function(t,e){return e||(e=oe),this.where(function(n){return e(n,t)}).any()},xn.count=function(t,e){return t?this.where(t,e).count():this.aggregate(0,function(t){return t+1})},xn.sum=function(t,e){return t?this.select(t,e).sum():this.aggregate(0,function(t,e){return t+e})},xn.minBy=function(t,e){return e||(e=se),m(this,t,function(t,n){return-1*e(t,n)})},xn.min=function(t){return this.minBy(re,t).select(function(t){return y(t)})},xn.maxBy=function(t,e){return e||(e=se),m(this,t,e)},xn.max=function(t){return this.maxBy(re,t).select(function(t){return y(t)})},xn.average=function(t,e){return t?this.select(t,e).average():this.scan({sum:0,count:0},function(t,e){return{sum:t.sum+e,count:t.count+1}}).finalValue().select(function(t){if(0===t.count)throw Error("The input sequence was empty");return t.sum/t.count})},xn.sequenceEqual=function(e,n){var r=this;return n||(n=oe),Array.isArray(e)?w(r,e,n):new hr(function(i){var o=!1,s=!1,u=[],c=[],a=r.subscribe(function(e){var r,o;if(c.length>0){o=c.shift();try{r=n(o,e)}catch(a){return i.onError(a),t}r||(i.onNext(!1),i.onCompleted())}else s?(i.onNext(!1),i.onCompleted()):u.push(e)},i.onError.bind(i),function(){o=!0,0===u.length&&(c.length>0?(i.onNext(!1),i.onCompleted()):s&&(i.onNext(!0),i.onCompleted()))});ae(e)&&(e=On(e));var h=e.subscribe(function(e){var r,s;if(u.length>0){s=u.shift();try{r=n(s,e)}catch(a){return i.onError(a),t}r||(i.onNext(!1),i.onCompleted())}else o?(i.onNext(!1),i.onCompleted()):c.push(e)},i.onError.bind(i),function(){s=!0,0===c.length&&(u.length>0?(i.onNext(!1),i.onCompleted()):o&&(i.onNext(!0),i.onCompleted()))});return new Qe(a,h)})},xn.elementAt=function(t){return g(this,t,!1)},xn.elementAtOrDefault=function(t,e){return g(this,t,!0,e)},xn.single=function(t,e){return t?this.where(t,e).single():E(this,!1)},xn.singleOrDefault=function(t,e,n){return t?this.where(t,n).singleOrDefault(null,e):E(this,!0,e)},xn.first=function(t,e){return t?this.where(t,e).first():x(this,!1)},xn.firstOrDefault=function(t,e){return t?this.where(t).firstOrDefault(null,e):x(this,!0,e)},xn.last=function(t,e){return t?this.where(t,e).last():C(this,!1)},xn.lastOrDefault=function(t,e,n){return t?this.where(t,n).lastOrDefault(null,e):C(this,!0,e)},xn.find=function(t,e){return D(this,t,e,!1)},xn.findIndex=function(t,e){return D(this,t,e,!0)},_n.start=function(t,e,n){return In(t,e,n)()};var In=_n.toAsync=function(e,n,r){return n||(n=hn),function(){var i=arguments,o=new dr;return n.schedule(function(){var n;try{n=e.apply(r,i)}catch(s){return o.onError(s),t}o.onNext(n),o.onCompleted()}),o.asObservable()}};_n.fromCallback=function(e,n,r,i){return n||(n=un),function(){var o=Ve.call(arguments,0);return new hr(function(s){return n.schedule(function(){function n(e){var n=e;if(i)try{n=i(arguments)}catch(r){return s.onError(r),t}else 1===n.length&&(n=n[0]);s.onNext(n),s.onCompleted()}o.push(n),e.apply(r,o)})})}},_n.fromNodeCallback=function(e,n,r,i){return n||(n=un),function(){var o=Ve.call(arguments,0);return new hr(function(s){return n.schedule(function(){function n(e){if(e)return s.onError(e),t;var n=Ve.call(arguments,1);if(i)try{n=i(n)}catch(r){return s.onError(r),t}else 1===n.length&&(n=n[0]);s.onNext(n),s.onCompleted()}o.push(n),e.apply(r,o)})})}};var Fn=X.angular&&angular.element?angular.element:X.jQuery?X.jQuery:X.Zepto?X.Zepto:null,Bn=!!X.Ember&&"function"==typeof X.Ember.addListener;_n.fromEvent=function(e,n,r){if(Bn)return Hn(function(t){Ember.addListener(e,n,t)},function(t){Ember.removeListener(e,n,t)},r);if(Fn){var i=Fn(e);return Hn(function(t){i.on(n,t)},function(t){i.off(n,t)},r)}return new hr(function(i){return A(e,n,function(e){var n=e;if(r)try{n=r(arguments)}catch(o){return i.onError(o),t}i.onNext(n)})}).publish().refCount()};var Hn=_n.fromEventPattern=function(e,n,r){return new hr(function(i){function o(e){var n=e;if(r)try{n=r(arguments)}catch(o){return i.onError(o),t}i.onNext(n)}var s=e(o);return Je(function(){n&&n(o,s)})}).publish().refCount()};_n.startAsync=function(t){var e;try{e=t()}catch(n){return Pn(n)}return On(e)};var Un=function(t){function e(t){var e=this.source.publish(),n=e.subscribe(t),r=Xe,i=this.subject.distinctUntilChanged().subscribe(function(t){t?r=e.connect():(r.dispose(),r=Xe)});return new Qe(n,r,i)}function n(n,r){this.source=n,this.subject=r||new pr,this.isPaused=!0,t.call(this,e)}return ze(n,t),n.prototype.pause=function(){this.isPaused!==!0&&(this.isPaused=!0,this.subject.onNext(!1))},n.prototype.resume=function(){this.isPaused!==!1&&(this.isPaused=!1,this.subject.onNext(!0))},n}(_n);xn.pausable=function(t){return new Un(this,t)};var Qn=function(t){function e(t){var e=[],n=!0,r=_(this.source,this.subject.distinctUntilChanged(),function(t,e){return{data:t,shouldFire:e}}).subscribe(function(r){if(r.shouldFire&&n&&t.onNext(r.data),r.shouldFire&&!n){for(;e.length>0;)t.onNext(e.shift());n=!0}else r.shouldFire||n?!r.shouldFire&&n&&(n=!1):e.push(r.data)},function(n){for(;e.length>0;)t.onNext(e.shift());t.onError(n)},function(){for(;e.length>0;)t.onNext(e.shift());t.onCompleted()});return this.subject.onNext(!1),r}function n(n,r){this.source=n,this.subject=r||new pr,this.isPaused=!0,t.call(this,e)}return ze(n,t),n.prototype.pause=function(){this.isPaused!==!0&&(this.isPaused=!0,this.subject.onNext(!1))},n.prototype.resume=function(){this.isPaused!==!1&&(this.isPaused=!1,this.subject.onNext(!0))},n}(_n);xn.pausableBuffered=function(t){return new Qn(this,t)},xn.controlled=function(t){return null==t&&(t=!0),new $n(this,t)};var $n=function(t){function e(t){return this.source.subscribe(t)}function n(n,r){t.call(this,e),this.subject=new Kn(r),this.source=n.multicast(this.subject).refCount()}return ze(n,t),n.prototype.request=function(t){return null==t&&(t=-1),this.subject.request(t)},n}(_n),Kn=ee.ControlledSubject=function(t){function n(t){return this.subject.subscribe(t)}function r(e){null==e&&(e=!0),t.call(this,n),this.subject=new pr,this.enableQueue=e,this.queue=e?[]:null,this.requestedCount=0,this.requestedDisposable=Xe,this.error=null,this.hasFailed=!1,this.hasCompleted=!1,this.controlledDisposable=Xe}return ze(r,t),Le(r.prototype,gn,{onCompleted:function(){e.call(this),this.hasCompleted=!0,this.enableQueue&&0!==this.queue.length||this.subject.onCompleted()},onError:function(t){e.call(this),this.hasFailed=!0,this.error=t,this.enableQueue&&0!==this.queue.length||this.subject.onError(t)},onNext:function(t){e.call(this);var n=!1;0===this.requestedCount?this.enableQueue&&this.queue.push(t):(-1!==this.requestedCount&&0===this.requestedCount--&&this.disposeCurrentRequest(),n=!0),n&&this.subject.onNext(t)},_processRequest:function(t){if(this.enableQueue){for(;this.queue.length>=t&&t>0;)this.subject.onNext(this.queue.shift()),t--;return 0!==this.queue.length?{numberOfItems:t,returnValue:!0}:{numberOfItems:t,returnValue:!1}}return this.hasFailed?(this.subject.onError(this.error),this.controlledDisposable.dispose(),this.controlledDisposable=Xe):this.hasCompleted&&(this.subject.onCompleted(),this.controlledDisposable.dispose(),this.controlledDisposable=Xe),{numberOfItems:t,returnValue:!1}},request:function(t){e.call(this),this.disposeCurrentRequest();var n=this,r=this._processRequest(t);return t=r.numberOfItems,r.returnValue?Xe:(this.requestedCount=t,this.requestedDisposable=Je(function(){n.requestedCount=0}),this.requestedDisposable)},disposeCurrentRequest:function(){this.requestedDisposable.dispose(),this.requestedDisposable=Xe},dispose:function(){this.isDisposed=!0,this.error=null,this.subject.dispose(),this.requestedDisposable.dispose()}}),r}(_n);xn.multicast=function(t,e){var n=this;return"function"==typeof t?new hr(function(r){var i=n.multicast(t());return new Qe(e(i).subscribe(r),i.connect())}):new Gn(n,t)},xn.publish=function(t){return t?this.multicast(function(){return new pr},t):this.multicast(new pr)},xn.share=function(){return this.publish(null).refCount()},xn.publishLast=function(t){return t?this.multicast(function(){return new dr},t):this.multicast(new dr)},xn.publishValue=function(t,e){return 2===arguments.length?this.multicast(function(){return new Xn(e)},t):this.multicast(new Xn(t))},xn.shareValue=function(t){return this.publishValue(t).refCount()},xn.replay=function(t,e,n,r){return t?this.multicast(function(){return new Zn(e,n,r)},t):this.multicast(new Zn(e,n,r))},xn.shareReplay=function(t,e,n){return this.replay(null,t,e,n).refCount()};var Jn=function(t,e){this.subject=t,this.observer=e};Jn.prototype.dispose=function(){if(!this.subject.isDisposed&&null!==this.observer){var t=this.subject.observers.indexOf(this.observer);this.subject.observers.splice(t,1),this.observer=null}};var Xn=ee.BehaviorSubject=function(t){function n(t){if(e.call(this),!this.isStopped)return this.observers.push(t),t.onNext(this.value),new Jn(this,t);var n=this.exception;return n?t.onError(n):t.onCompleted(),Xe}function r(e){t.call(this,n),this.value=e,this.observers=[],this.isDisposed=!1,this.isStopped=!1,this.exception=null}return ze(r,t),Le(r.prototype,gn,{hasObservers:function(){return this.observers.length>0},onCompleted:function(){if(e.call(this),!this.isStopped){var t=this.observers.slice(0);this.isStopped=!0;for(var n=0,r=t.length;r>n;n++)t[n].onCompleted();this.observers=[]}},onError:function(t){if(e.call(this),!this.isStopped){var n=this.observers.slice(0);this.isStopped=!0,this.exception=t;for(var r=0,i=n.length;i>r;r++)n[r].onError(t);this.observers=[]}},onNext:function(t){if(e.call(this),!this.isStopped){this.value=t;for(var n=this.observers.slice(0),r=0,i=n.length;i>r;r++)n[r].onNext(t)}},dispose:function(){this.isDisposed=!0,this.observers=null,this.value=null,this.exception=null}}),r}(_n),Zn=ee.ReplaySubject=function(t){function n(t,e){this.subject=t,this.observer=e}function r(t){var r=new Nn(this.scheduler,t),i=new n(this,r);e.call(this),this._trim(this.scheduler.now()),this.observers.push(r);for(var o=this.q.length,s=0,u=this.q.length;u>s;s++)r.onNext(this.q[s].value);return this.hasError?(o++,r.onError(this.error)):this.isStopped&&(o++,r.onCompleted()),r.ensureActive(o),i}function i(e,n,i){this.bufferSize=null==e?Number.MAX_VALUE:e,this.windowSize=null==n?Number.MAX_VALUE:n,this.scheduler=i||cn,this.q=[],this.observers=[],this.isStopped=!1,this.isDisposed=!1,this.hasError=!1,this.error=null,t.call(this,r)}return n.prototype.dispose=function(){if(this.observer.dispose(),!this.subject.isDisposed){var t=this.subject.observers.indexOf(this.observer);this.subject.observers.splice(t,1)}},ze(i,t),Le(i.prototype,gn,{hasObservers:function(){return this.observers.length>0},_trim:function(t){for(;this.q.length>this.bufferSize;)this.q.shift();for(;this.q.length>0&&t-this.q[0].interval>this.windowSize;)this.q.shift()},onNext:function(t){var n;if(e.call(this),!this.isStopped){var r=this.scheduler.now();this.q.push({interval:r,value:t}),this._trim(r);for(var i=this.observers.slice(0),o=0,s=i.length;s>o;o++)n=i[o],n.onNext(t),n.ensureActive()}},onError:function(t){var n;if(e.call(this),!this.isStopped){this.isStopped=!0,this.error=t,this.hasError=!0;var r=this.scheduler.now();this._trim(r);for(var i=this.observers.slice(0),o=0,s=i.length;s>o;o++)n=i[o],n.onError(t),n.ensureActive();this.observers=[]}},onCompleted:function(){var t;if(e.call(this),!this.isStopped){this.isStopped=!0;var n=this.scheduler.now();this._trim(n);for(var r=this.observers.slice(0),i=0,o=r.length;o>i;i++)t=r[i],t.onCompleted(),t.ensureActive();this.observers=[]}},dispose:function(){this.isDisposed=!0,this.observers=null}}),i}(_n),Gn=ee.ConnectableObservable=function(t){function e(e,n){function r(t){return i.subject.subscribe(t)}var i={subject:n,source:e.asObservable(),hasSubscription:!1,subscription:null};this.connect=function(){return i.hasSubscription||(i.hasSubscription=!0,i.subscription=new Qe(i.source.subscribe(i.subject),Je(function(){i.hasSubscription=!1}))),i.subscription},t.call(this,r)}return ze(e,t),e.prototype.connect=function(){return this.connect()},e.prototype.refCount=function(){var t=null,e=0,n=this;return new hr(function(r){var i,o;return e++,i=1===e,o=n.subscribe(r),i&&(t=n.connect()),Je(function(){o.dispose(),e--,0===e&&t.dispose()})})},e}(_n),Yn=[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],tr="no such key",er="duplicate key",nr=function(){var t=0;return function(e){if(null==e)throw Error(tr);if("string"==typeof e)return j(e);if("number"==typeof e)return k(e);if("boolean"==typeof e)return e===!0?1:0;if(e instanceof Date)return e.getTime();if(e.getHashCode)return e.getHashCode();var n=17*t++;return e.getHashCode=function(){return n},n}}(),rr=function(t,e){if(0>t)throw Error("out of range");t>0&&this._initialize(t),this.comparer=e||oe,this.freeCount=0,this.size=0,this.freeList=-1};rr.prototype._initialize=function(t){var e,n=W(t);for(this.buckets=Array(n),this.entries=Array(n),e=0;n>e;e++)this.buckets[e]=-1,this.entries[e]=R();this.freeList=-1},rr.prototype.count=function(){return this.size},rr.prototype.add=function(t,e){return this._insert(t,e,!0)},rr.prototype._insert=function(e,n,r){this.buckets||this._initialize(0);for(var i,o=2147483647&nr(e),s=o%this.buckets.length,u=this.buckets[s];u>=0;u=this.entries[u].next)if(this.entries[u].hashCode===o&&this.comparer(this.entries[u].key,e)){if(r)throw Error(er);return this.entries[u].value=n,t}this.freeCount>0?(i=this.freeList,this.freeList=this.entries[i].next,--this.freeCount):(this.size===this.entries.length&&(this._resize(),s=o%this.buckets.length),i=this.size,++this.size),this.entries[i].hashCode=o,this.entries[i].next=this.buckets[s],this.entries[i].key=e,this.entries[i].value=n,this.buckets[s]=i},rr.prototype._resize=function(){var t=W(2*this.size),e=Array(t);for(r=0;e.length>r;++r)e[r]=-1;var n=Array(t);for(r=0;this.size>r;++r)n[r]=this.entries[r];for(var r=this.size;t>r;++r)n[r]=R();for(var i=0;this.size>i;++i){var o=n[i].hashCode%t;n[i].next=e[o],e[o]=i}this.buckets=e,this.entries=n},rr.prototype.remove=function(t){if(this.buckets)for(var e=2147483647&nr(t),n=e%this.buckets.length,r=-1,i=this.buckets[n];i>=0;i=this.entries[i].next){if(this.entries[i].hashCode===e&&this.comparer(this.entries[i].key,t))return 0>r?this.buckets[n]=this.entries[i].next:this.entries[r].next=this.entries[i].next,this.entries[i].hashCode=-1,this.entries[i].next=this.freeList,this.entries[i].key=null,this.entries[i].value=null,this.freeList=i,++this.freeCount,!0;r=i}return!1},rr.prototype.clear=function(){var t,e;if(!(0>=this.size)){for(t=0,e=this.buckets.length;e>t;++t)this.buckets[t]=-1;for(t=0;this.size>t;++t)this.entries[t]=R();this.freeList=-1,this.size=0}},rr.prototype._findEntry=function(t){if(this.buckets)for(var e=2147483647&nr(t),n=this.buckets[e%this.buckets.length];n>=0;n=this.entries[n].next)if(this.entries[n].hashCode===e&&this.comparer(this.entries[n].key,t))return n;return-1},rr.prototype.count=function(){return this.size-this.freeCount},rr.prototype.tryGetValue=function(e){var n=this._findEntry(e);return n>=0?this.entries[n].value:t},rr.prototype.getValues=function(){var t=0,e=[];if(this.entries)for(var n=0;this.size>n;n++)this.entries[n].hashCode>=0&&(e[t++]=this.entries[n].value);return e},rr.prototype.get=function(t){var e=this._findEntry(t);if(e>=0)return this.entries[e].value;throw Error(tr)},rr.prototype.set=function(t,e){this._insert(t,e,!1)},rr.prototype.containskey=function(t){return this._findEntry(t)>=0},xn.join=function(e,n,r,i){var o=this;return new hr(function(s){var u=new Qe,c=!1,a=0,h=new rr,l=!1,f=0,p=new rr;return u.add(o.subscribe(function(e){var r,o,l,f,d=a++,v=new Ge;h.add(d,e),u.add(v),o=function(){return h.remove(d)&&0===h.count()&&c&&s.onCompleted(),u.remove(v)};try{r=n(e)}catch(b){return s.onError(b),t}v.setDisposable(r.take(1).subscribe(ne,s.onError.bind(s),function(){o()})),f=p.getValues();for(var m=0;f.length>m;m++){try{l=i(e,f[m])}catch(y){return s.onError(y),t}s.onNext(l)}},s.onError.bind(s),function(){c=!0,(l||0===h.count())&&s.onCompleted()})),u.add(e.subscribe(function(e){var n,o,c,a,d=f++,v=new Ge;p.add(d,e),u.add(v),o=function(){return p.remove(d)&&0===p.count()&&l&&s.onCompleted(),u.remove(v)};try{n=r(e)}catch(b){return s.onError(b),t}v.setDisposable(n.take(1).subscribe(ne,s.onError.bind(s),function(){o()})),a=h.getValues();for(var m=0;a.length>m;m++){try{c=i(a[m],e)}catch(b){return s.onError(b),t +}s.onNext(c)}},s.onError.bind(s),function(){l=!0,(c||0===p.count())&&s.onCompleted()})),u})},xn.groupJoin=function(e,n,r,i){var o=this;return new hr(function(s){var u=function(){},c=new Qe,a=new tn(c),h=new rr,l=new rr,f=0,p=0;return c.add(o.subscribe(function(e){var r=new pr,o=f++;h.add(o,r);var p,d,v,b,m;try{m=i(e,Me(r,a))}catch(y){for(v=h.getValues(),p=0,d=v.length;d>p;p++)v[p].onError(y);return s.onError(y),t}for(s.onNext(m),b=l.getValues(),p=0,d=b.length;d>p;p++)r.onNext(b[p]);var w=new Ge;c.add(w);var g,E=function(){h.remove(o)&&r.onCompleted(),c.remove(w)};try{g=n(e)}catch(y){for(v=h.getValues(),p=0,d=h.length;d>p;p++)v[p].onError(y);return s.onError(y),t}w.setDisposable(g.take(1).subscribe(u,function(t){for(v=h.getValues(),p=0,d=v.length;d>p;p++)v[p].onError(t);s.onError(t)},E))},function(t){for(var e=h.getValues(),n=0,r=e.length;r>n;n++)e[n].onError(t);s.onError(t)},s.onCompleted.bind(s))),c.add(e.subscribe(function(e){var n,i,o,a=p++;l.add(a,e);var f=new Ge;c.add(f);var d,v=function(){l.remove(a),c.remove(f)};try{d=r(e)}catch(b){for(n=h.getValues(),i=0,o=h.length;o>i;i++)n[i].onError(b);return s.onError(b),t}for(f.setDisposable(d.take(1).subscribe(u,function(t){for(n=h.getValues(),i=0,o=h.length;o>i;i++)n[i].onError(t);s.onError(t)},v)),n=h.getValues(),i=0,o=n.length;o>i;i++)n[i].onNext(e)},function(t){for(var e=h.getValues(),n=0,r=e.length;r>n;n++)e[n].onError(t);s.onError(t)})),a})},xn.buffer=function(){return this.window.apply(this,arguments).selectMany(function(t){return t.toArray()})},xn.window=function(t,e){return 1===arguments.length&&"function"!=typeof arguments[0]?P.call(this,t):"function"==typeof t?T.call(this,t):q.call(this,t,e)},xn.pairwise=function(){var t=this;return new hr(function(e){var n,r=!1;return t.subscribe(function(t){r?e.onNext([n,t]):r=!0,n=t},e.onError.bind(e),e.onCompleted.bind(e))})},xn.partition=function(t,e){var n=this.publish().refCount();return[n.filter(t,e),n.filter(function(n,r,i){return!t.call(e,n,r,i)})]},xn.letBind=xn.let=function(t){return t(this)},_n["if"]=_n.ifThen=function(t,e,n){return Wn(function(){return n||(n=jn()),ae(e)&&(e=On(e)),ae(n)&&(n=On(n)),"function"==typeof n.now&&(n=jn(n)),t()?e:n})},_n["for"]=_n.forIn=function(t,e){return wn(t,e).concat()};var ir=_n["while"]=_n.whileDo=function(t,e){return ae(e)&&(e=On(e)),V(t,e).concat()};xn.doWhile=function(t){return zn([this,ir(t,this)])},_n["case"]=_n.switchCase=function(t,e,n){return Wn(function(){n||(n=jn()),"function"==typeof n.now&&(n=jn(n));var r=e[t()];return ae(r)&&(r=On(r)),r||n})},xn.expand=function(e,n){n||(n=un);var r=this;return new hr(function(i){var o=[],s=new Ye,u=new Qe(s),c=0,a=!1,h=function(){var r=!1;o.length>0&&(r=!a,a=!0),r&&s.setDisposable(n.scheduleRecursive(function(n){var r;if(!(o.length>0))return a=!1,t;r=o.shift();var s=new Ge;u.add(s),s.setDisposable(r.subscribe(function(t){i.onNext(t);var n=null;try{n=e(t)}catch(r){i.onError(r)}o.push(n),c++,h()},i.onError.bind(i),function(){u.remove(s),c--,0===c&&i.onCompleted()})),n()}))};return o.push(r),c++,h(),u})},_n.forkJoin=function(){var e=h(arguments,0);return new hr(function(n){var r=e.length;if(0===r)return n.onCompleted(),Xe;for(var i=new Qe,o=!1,s=Array(r),u=Array(r),c=Array(r),a=0;r>a;a++)(function(a){var h=e[a];ae(h)&&(h=On(h)),i.add(h.subscribe(function(t){o||(s[a]=!0,c[a]=t)},function(t){o=!0,n.onError(t),i.dispose()},function(){if(!o){if(!s[a])return n.onCompleted(),t;u[a]=!0;for(var e=0;r>e;e++)if(!u[e])return;o=!0,n.onNext(c),n.onCompleted()}}))})(a);return i})},xn.forkJoin=function(e,n){var r=this;return new hr(function(i){var o,s,u=!1,c=!1,a=!1,h=!1,l=new Ge,f=new Ge;return ae(e)&&(e=On(e)),l.setDisposable(r.subscribe(function(t){a=!0,o=t},function(t){f.dispose(),i.onError(t)},function(){if(u=!0,c)if(a)if(h){var e;try{e=n(o,s)}catch(r){return i.onError(r),t}i.onNext(e),i.onCompleted()}else i.onCompleted();else i.onCompleted()})),f.setDisposable(e.subscribe(function(t){h=!0,s=t},function(t){l.dispose(),i.onError(t)},function(){if(c=!0,u)if(a)if(h){var e;try{e=n(o,s)}catch(r){return i.onError(r),t}i.onNext(e),i.onCompleted()}else i.onCompleted();else i.onCompleted()})),new Qe(l,f)})},xn.manySelect=function(t,e){e||(e=un);var n=this;return Wn(function(){var r;return n.select(function(t){var e=new or(t);return r&&r.onNext(t),r=e,e}).doAction(ne,function(t){r&&r.onError(t)},function(){r&&r.onCompleted()}).observeOn(e).select(function(e,n,r){return t(e,n,r)})})};var or=function(t){function e(t){var e=this,n=new Qe;return n.add(cn.schedule(function(){t.onNext(e.head),n.add(e.tail.mergeObservable().subscribe(t))})),n}function n(n){t.call(this,e),this.head=n,this.tail=new dr}return ze(n,t),Le(n.prototype,gn,{onCompleted:function(){this.onNext(_n.empty())},onError:function(t){this.onNext(_n.throwException(t))},onNext:function(t){this.tail.onNext(t),this.tail.onCompleted()}}),n}(_n),sr=function(){function t(){this.keys=[],this.values=[]}return t.prototype["delete"]=function(t){var e=this.keys.indexOf(t);return-1!==e&&(this.keys.splice(e,1),this.values.splice(e,1)),-1!==e},t.prototype.get=function(t,e){var n=this.keys.indexOf(t);return-1!==n?this.values[n]:e},t.prototype.set=function(t,e){var n=this.keys.indexOf(t);-1!==n&&(this.values[n]=e),this.values[this.keys.push(t)-1]=e},t.prototype.size=function(){return this.keys.length},t.prototype.has=function(t){return-1!==this.keys.indexOf(t)},t.prototype.getKeys=function(){return this.keys.slice(0)},t.prototype.getValues=function(){return this.values.slice(0)},t}();z.prototype.and=function(t){var e=this.patterns.slice(0);return e.push(t),new z(e)},z.prototype.then=function(t){return new L(this,t)},L.prototype.activate=function(e,n,r){for(var i=this,o=[],s=0,u=this.expression.patterns.length;u>s;s++)o.push(M(e,this.expression.patterns[s],n.onError.bind(n)));var c=new I(o,function(){var e;try{e=i.selector.apply(i,arguments)}catch(r){return n.onError(r),t}n.onNext(e)},function(){for(var t=0,e=o.length;e>t;t++)o[t].removeActivePlan(c);r(c)});for(s=0,u=o.length;u>s;s++)o[s].addActivePlan(c);return c},I.prototype.dequeue=function(){for(var t=this.joinObservers.getValues(),e=0,n=t.length;n>e;e++)t[e].queue.shift()},I.prototype.match=function(){var t,e,n,r,i,o=!0;for(e=0,n=this.joinObserverArray.length;n>e;e++)if(0===this.joinObserverArray[e].queue.length){o=!1;break}if(o){for(t=[],r=!1,e=0,n=this.joinObserverArray.length;n>e;e++)t.push(this.joinObserverArray[e].queue[0]),"C"===this.joinObserverArray[e].queue[0].kind&&(r=!0);if(r)this.onCompleted();else{for(this.dequeue(),i=[],e=0;t.length>e;e++)i.push(t[e].value);this.onNext.apply(this,i)}}};var ur=function(e){function n(t,n){e.call(this),this.source=t,this.onError=n,this.queue=[],this.activePlans=[],this.subscription=new Ge,this.isDisposed=!1}ze(n,e);var r=n.prototype;return r.next=function(e){if(!this.isDisposed){if("E"===e.kind)return this.onError(e.exception),t;this.queue.push(e);for(var n=this.activePlans.slice(0),r=0,i=n.length;i>r;r++)n[r].match()}},r.error=ne,r.completed=ne,r.addActivePlan=function(t){this.activePlans.push(t)},r.subscribe=function(){this.subscription.setDisposable(this.source.materialize().subscribe(this))},r.removeActivePlan=function(t){var e=this.activePlans.indexOf(t);this.activePlans.splice(e,1),0===this.activePlans.length&&this.dispose()},r.dispose=function(){e.prototype.dispose.call(this),this.isDisposed||(this.isDisposed=!0,this.subscription.dispose())},n}(Cn);xn.and=function(t){return new z([this,t])},xn.then=function(t){return new z([this]).then(t)},_n.when=function(){var t=h(arguments,0);return new hr(function(e){var n,r,i,o,s,u,c=[],a=new sr;u=En(e.onNext.bind(e),function(t){for(var n=a.getValues(),r=0,i=n.length;i>r;r++)n[r].onError(t);e.onError(t)},e.onCompleted.bind(e));try{for(r=0,i=t.length;i>r;r++)c.push(t[r].activate(a,u,function(t){var e=c.indexOf(t);c.splice(e,1),0===c.length&&u.onCompleted()}))}catch(h){Pn(h).subscribe(e)}for(n=new Qe,s=a.getValues(),r=0,i=s.length;i>r;r++)o=s[r],o.subscribe(),n.add(o);return n})};var cr=_n.interval=function(t,e){return e||(e=hn),U(t,t,e)},ar=_n.timer=function(e,n,r){var i;return r||(r=hn),n!==t&&"number"==typeof n?i=n:n!==t&&"object"==typeof n&&(r=n),e instanceof Date&&i===t?F(e.getTime(),r):e instanceof Date&&i!==t?(i=n,B(e.getTime(),i,r)):i===t?H(e,r):U(e,i,r)};xn.delay=function(t,e){return e||(e=hn),t instanceof Date?$.call(this,t.getTime(),e):Q.call(this,t,e)},xn.throttle=function(t,e){return e||(e=hn),this.throttleWithSelector(function(){return ar(t,e)})},xn.windowWithTime=function(e,n,r){var i,o=this;return n===t&&(i=e),r===t&&(r=hn),"number"==typeof n?i=n:"object"==typeof n&&(i=e,r=n),new hr(function(t){function n(){var e=new Ge,o=!1,s=!1;l.setDisposable(e),a===c?(o=!0,s=!0):c>a?o=!0:s=!0;var p=o?a:c,d=p-f;f=p,o&&(a+=i),s&&(c+=i),e.setDisposable(r.scheduleWithRelative(d,function(){var e;s&&(e=new pr,h.push(e),t.onNext(Me(e,u))),o&&(e=h.shift(),e.onCompleted()),n()}))}var s,u,c=i,a=e,h=[],l=new Ye,f=0;return s=new Qe(l),u=new tn(s),h.push(new pr),t.onNext(Me(h[0],u)),n(),s.add(o.subscribe(function(t){var e,n;for(e=0;h.length>e;e++)n=h[e],n.onNext(t)},function(e){var n,r;for(n=0;h.length>n;n++)r=h[n],r.onError(e);t.onError(e)},function(){var e,n;for(e=0;h.length>e;e++)n=h[e],n.onCompleted();t.onCompleted()})),u})},xn.windowWithTimeOrCount=function(t,e,n){var r=this;return n||(n=hn),new hr(function(i){var o,s,u,c,a=0,h=new Ye,l=0;return s=new Qe(h),u=new tn(s),o=function(e){var r=new Ge;h.setDisposable(r),r.setDisposable(n.scheduleWithRelative(t,function(){var t;e===l&&(a=0,t=++l,c.onCompleted(),c=new pr,i.onNext(Me(c,u)),o(t))}))},c=new pr,i.onNext(Me(c,u)),o(0),s.add(r.subscribe(function(t){var n=0,r=!1;c.onNext(t),a++,a===e&&(r=!0,a=0,n=++l,c.onCompleted(),c=new pr,i.onNext(Me(c,u))),r&&o(n)},function(t){c.onError(t),i.onError(t)},function(){c.onCompleted(),i.onCompleted()})),u})},xn.bufferWithTime=function(){return this.windowWithTime.apply(this,arguments).selectMany(function(t){return t.toArray()})},xn.bufferWithTimeOrCount=function(t,e,n){return this.windowWithTimeOrCount(t,e,n).selectMany(function(t){return t.toArray()})},xn.timeInterval=function(t){var e=this;return t||(t=hn),Wn(function(){var n=t.now();return e.select(function(e){var r=t.now(),i=r-n;return n=r,{value:e,interval:i}})})},xn.timestamp=function(t){return t||(t=hn),this.select(function(e){return{value:e,timestamp:t.now()}})},xn.sample=function(t,e){return e||(e=hn),"number"==typeof t?K(this,cr(t,e)):K(this,t)},xn.timeout=function(t,e,n){e||(e=Pn(Error("Timeout"))),n||(n=hn);var r=this,i=t instanceof Date?"scheduleWithAbsolute":"scheduleWithRelative";return new hr(function(o){var s=0,u=new Ge,c=new Ye,a=!1,h=new Ye;c.setDisposable(u);var l=function(){var r=s;h.setDisposable(n[i](t,function(){s===r&&(ae(e)&&(e=On(e)),c.setDisposable(e.subscribe(o)))}))};return l(),u.setDisposable(r.subscribe(function(t){a||(s++,o.onNext(t),l())},function(t){a||(s++,o.onError(t))},function(){a||(s++,o.onCompleted())})),new Qe(c,h)})},_n.generateWithAbsoluteTime=function(e,n,r,i,o,s){return s||(s=hn),new hr(function(u){var c,a,h=!0,l=!1,f=e;return s.scheduleRecursiveWithAbsolute(s.now(),function(e){l&&u.onNext(c);try{h?h=!1:f=r(f),l=n(f),l&&(c=i(f),a=o(f))}catch(s){return u.onError(s),t}l?e(a):u.onCompleted()})})},_n.generateWithRelativeTime=function(e,n,r,i,o,s){return s||(s=hn),new hr(function(u){var c,a,h=!0,l=!1,f=e;return s.scheduleRecursiveWithRelative(0,function(e){l&&u.onNext(c);try{h?h=!1:f=r(f),l=n(f),l&&(c=i(f),a=o(f))}catch(s){return u.onError(s),t}l?e(a):u.onCompleted()})})},xn.delaySubscription=function(t,e){return e||(e=hn),this.delayWithSelector(ar(t,e),function(){return jn()})},xn.delayWithSelector=function(e,n){var r,i,o=this;return"function"==typeof e?i=e:(r=e,i=n),new hr(function(e){var n=new Qe,s=!1,u=function(){s&&0===n.length&&e.onCompleted()},c=new Ye,a=function(){c.setDisposable(o.subscribe(function(r){var o;try{o=i(r)}catch(s){return e.onError(s),t}var c=new Ge;n.add(c),c.setDisposable(o.subscribe(function(){e.onNext(r),n.remove(c),u()},e.onError.bind(e),function(){e.onNext(r),n.remove(c),u()}))},e.onError.bind(e),function(){s=!0,c.dispose(),u()}))};return r?c.setDisposable(r.subscribe(function(){a()},e.onError.bind(e),function(){a()})):a(),new Qe(c,n)})},xn.timeoutWithSelector=function(e,n,r){if(1===arguments.length){n=e;var e=Rn()}r||(r=Pn(Error("Timeout")));var i=this;return new hr(function(o){var s=new Ye,u=new Ye,c=new Ge;s.setDisposable(c);var a=0,h=!1,l=function(t){var e=a,n=function(){return a===e},i=new Ge;u.setDisposable(i),i.setDisposable(t.subscribe(function(){n()&&s.setDisposable(r.subscribe(o)),i.dispose()},function(t){n()&&o.onError(t)},function(){n()&&s.setDisposable(r.subscribe(o))}))};l(e);var f=function(){var t=!h;return t&&a++,t};return c.setDisposable(i.subscribe(function(e){if(f()){o.onNext(e);var r;try{r=n(e)}catch(i){return o.onError(i),t}l(r)}},function(t){f()&&o.onError(t)},function(){f()&&o.onCompleted()})),new Qe(s,u)})},xn.throttleWithSelector=function(e){var n=this;return new hr(function(r){var i,o=!1,s=new Ye,u=0,c=n.subscribe(function(n){var c;try{c=e(n)}catch(a){return r.onError(a),t}o=!0,i=n,u++;var h=u,l=new Ge;s.setDisposable(l),l.setDisposable(c.subscribe(function(){o&&u===h&&r.onNext(i),o=!1,l.dispose()},r.onError.bind(r),function(){o&&u===h&&r.onNext(i),o=!1,l.dispose()}))},function(t){s.dispose(),r.onError(t),o=!1,u++},function(){s.dispose(),o&&r.onNext(i),r.onCompleted(),o=!1,u++});return new Qe(c,s)})},xn.skipLastWithTime=function(t,e){e||(e=hn);var n=this;return new hr(function(r){var i=[];return n.subscribe(function(n){var o=e.now();for(i.push({interval:o,value:n});i.length>0&&o-i[0].interval>=t;)r.onNext(i.shift().value)},r.onError.bind(r),function(){for(var n=e.now();i.length>0&&n-i[0].interval>=t;)r.onNext(i.shift().value);r.onCompleted()})})},xn.takeLastWithTime=function(t,e,n){return this.takeLastBufferWithTime(t,e).selectMany(function(t){return kn(t,n)})},xn.takeLastBufferWithTime=function(t,e){var n=this;return e||(e=hn),new hr(function(r){var i=[];return n.subscribe(function(n){var r=e.now();for(i.push({interval:r,value:n});i.length>0&&r-i[0].interval>=t;)i.shift()},r.onError.bind(r),function(){for(var n=e.now(),o=[];i.length>0;){var s=i.shift();t>=n-s.interval&&o.push(s.value)}r.onNext(o),r.onCompleted()})})},xn.takeWithTime=function(t,e){var n=this;return e||(e=hn),new hr(function(r){var i=e.scheduleWithRelative(t,function(){r.onCompleted()});return new Qe(i,n.subscribe(r))})},xn.skipWithTime=function(t,e){var n=this;return e||(e=hn),new hr(function(r){var i=!1,o=e.scheduleWithRelative(t,function(){i=!0}),s=n.subscribe(function(t){i&&r.onNext(t)},r.onError.bind(r),r.onCompleted.bind(r));return new Qe(o,s)})},xn.skipUntilWithTime=function(t,e){e||(e=hn);var n=this,r=t instanceof Date?"scheduleWithAbsolute":"scheduleWithRelative";return new hr(function(i){var o=!1;return new Qe(e[r](t,function(){o=!0}),n.subscribe(function(t){o&&i.onNext(t)},i.onError.bind(i),i.onCompleted.bind(i)))})},xn.takeUntilWithTime=function(t,e){e||(e=hn);var n=this,r=t instanceof Date?"scheduleWithAbsolute":"scheduleWithRelative";return new hr(function(i){return new Qe(e[r](t,function(){i.onCompleted()}),n.subscribe(i))})},xn.exclusive=function(){var t=this;return new hr(function(e){var n=!1,r=!1,i=new Ge,o=new Qe;return o.add(i),i.setDisposable(t.subscribe(function(t){if(!n){n=!0,ae(t)&&(t=On(t));var i=new Ge;o.add(i),i.setDisposable(t.subscribe(e.onNext.bind(e),e.onError.bind(e),function(){o.remove(i),n=!1,r&&1===o.length&&e.onCompleted()}))}},e.onError.bind(e),function(){r=!0,n||1!==o.length||e.onCompleted()})),o})},xn.exclusiveMap=function(e,n){var r=this;return new hr(function(i){var o=0,s=!1,u=!0,c=new Ge,a=new Qe;return a.add(c),c.setDisposable(r.subscribe(function(r){s||(s=!0,innerSubscription=new Ge,a.add(innerSubscription),ae(r)&&(r=On(r)),innerSubscription.setDisposable(r.subscribe(function(s){var u;try{u=e.call(n,s,o++,r)}catch(c){return i.onError(c),t}i.onNext(u)},i.onError.bind(i),function(){a.remove(innerSubscription),s=!1,u&&1===a.length&&i.onCompleted()})))},i.onError.bind(i),function(){u=!0,1!==a.length||s||i.onCompleted()})),a})},ee.VirtualTimeScheduler=function(t){function e(){throw Error("Not implemented")}function n(){return this.toDateTimeOffset(this.clock)}function r(t,e){return this.scheduleAbsoluteWithState(t,this.clock,e)}function i(t,e,n){return this.scheduleRelativeWithState(t,this.toRelative(e),n)}function o(t,e,n){return this.scheduleRelativeWithState(t,this.toRelative(e-this.now()),n)}function s(t,e){return e(),Xe}function u(e,s){this.clock=e,this.comparer=s,this.isEnabled=!1,this.queue=new He(1024),t.call(this,n,r,i,o)}ze(u,t);var c=u.prototype;return c.add=e,c.toDateTimeOffset=e,c.toRelative=e,c.schedulePeriodicWithState=function(t,e,n){var r=new sn(this,t,e,n);return r.start()},c.scheduleRelativeWithState=function(t,e,n){var r=this.add(this.clock,e);return this.scheduleAbsoluteWithState(t,r,n)},c.scheduleRelative=function(t,e){return this.scheduleRelativeWithState(e,t,s)},c.start=function(){var t;if(!this.isEnabled){this.isEnabled=!0;do t=this.getNext(),null!==t?(this.comparer(t.dueTime,this.clock)>0&&(this.clock=t.dueTime),t.invoke()):this.isEnabled=!1;while(this.isEnabled)}},c.stop=function(){this.isEnabled=!1},c.advanceTo=function(t){var e,n=this.comparer(this.clock,t);if(this.comparer(this.clock,t)>0)throw Error(le);if(0!==n&&!this.isEnabled){this.isEnabled=!0;do e=this.getNext(),null!==e&&0>=this.comparer(e.dueTime,t)?(this.comparer(e.dueTime,this.clock)>0&&(this.clock=e.dueTime),e.invoke()):this.isEnabled=!1;while(this.isEnabled);this.clock=t}},c.advanceBy=function(t){var e=this.add(this.clock,t),n=this.comparer(this.clock,e);if(n>0)throw Error(le);0!==n&&this.advanceTo(e)},c.sleep=function(t){var e=this.add(this.clock,t);if(this.comparer(this.clock,e)>=0)throw Error(le);this.clock=e},c.getNext=function(){for(var t;this.queue.length>0;){if(t=this.queue.peek(),!t.isCancelled())return t;this.queue.dequeue()}return null},c.scheduleAbsolute=function(t,e){return this.scheduleAbsoluteWithState(e,t,s)},c.scheduleAbsoluteWithState=function(t,e,n){var r=this,i=function(t,e){return r.queue.remove(o),n(t,e)},o=new en(r,t,i,e,r.comparer);return r.queue.enqueue(o),o.disposable},u}(rn),ee.HistoricalScheduler=function(t){function e(e,n){var r=null==e?0:e,i=n||se;t.call(this,r,i)}ze(e,t);var n=e.prototype;return n.add=function(t,e){return t+e},n.toDateTimeOffset=function(t){return new Date(t).getTime()},n.toRelative=function(t){return t},e}(ee.VirtualTimeScheduler);var hr=ee.AnonymousObservable=function(e){function n(e){return e===t?e=Xe:"function"==typeof e&&(e=Je(e)),e}function r(i){function o(t){var e=function(){try{r.setDisposable(n(i(r)))}catch(t){if(!r.fail(t))throw t}},r=new lr(t);return cn.scheduleRequired()?cn.schedule(e):e(),r}return this instanceof r?(e.call(this,o),t):new r(i)}return ze(r,e),r}(_n),lr=function(t){function e(e){t.call(this),this.observer=e,this.m=new Ge}ze(e,t);var n=e.prototype;return n.next=function(t){var e=!1;try{this.observer.onNext(t),e=!0}catch(n){throw n}finally{e||this.dispose()}},n.error=function(t){try{this.observer.onError(t)}catch(e){throw e}finally{this.dispose()}},n.completed=function(){try{this.observer.onCompleted()}catch(t){throw t}finally{this.dispose()}},n.setDisposable=function(t){this.m.setDisposable(t)},n.getDisposable=function(){return this.m.getDisposable()},n.disposable=function(t){return arguments.length?this.getDisposable():setDisposable(t)},n.dispose=function(){t.prototype.dispose.call(this),this.m.dispose()},e}(Cn),fr=function(t){function e(t){return this.underlyingObservable.subscribe(t)}function n(n,r,i){t.call(this,e),this.key=n,this.underlyingObservable=i?new hr(function(t){return new Qe(i.getDisposable(),r.subscribe(t))}):r}return ze(n,t),n}(_n),pr=ee.Subject=function(t){function n(t){return e.call(this),this.isStopped?this.exception?(t.onError(this.exception),Xe):(t.onCompleted(),Xe):(this.observers.push(t),new Jn(this,t))}function r(){t.call(this,n),this.isDisposed=!1,this.isStopped=!1,this.observers=[]}return ze(r,t),Le(r.prototype,gn,{hasObservers:function(){return this.observers.length>0},onCompleted:function(){if(e.call(this),!this.isStopped){var t=this.observers.slice(0);this.isStopped=!0;for(var n=0,r=t.length;r>n;n++)t[n].onCompleted();this.observers=[]}},onError:function(t){if(e.call(this),!this.isStopped){var n=this.observers.slice(0);this.isStopped=!0,this.exception=t;for(var r=0,i=n.length;i>r;r++)n[r].onError(t);this.observers=[]}},onNext:function(t){if(e.call(this),!this.isStopped)for(var n=this.observers.slice(0),r=0,i=n.length;i>r;r++)n[r].onNext(t)},dispose:function(){this.isDisposed=!0,this.observers=null}}),r.create=function(t,e){return new vr(t,e)},r}(_n),dr=ee.AsyncSubject=function(t){function n(t){if(e.call(this),!this.isStopped)return this.observers.push(t),new Jn(this,t);var n=this.exception,r=this.hasValue,i=this.value;return n?t.onError(n):r?(t.onNext(i),t.onCompleted()):t.onCompleted(),Xe}function r(){t.call(this,n),this.isDisposed=!1,this.isStopped=!1,this.value=null,this.hasValue=!1,this.observers=[],this.exception=null}return ze(r,t),Le(r.prototype,gn,{hasObservers:function(){return e.call(this),this.observers.length>0},onCompleted:function(){var t,n,r;if(e.call(this),!this.isStopped){this.isStopped=!0;var i=this.observers.slice(0),o=this.value,s=this.hasValue;if(s)for(n=0,r=i.length;r>n;n++)t=i[n],t.onNext(o),t.onCompleted();else for(n=0,r=i.length;r>n;n++)i[n].onCompleted();this.observers=[]}},onError:function(t){if(e.call(this),!this.isStopped){var n=this.observers.slice(0);this.isStopped=!0,this.exception=t;for(var r=0,i=n.length;i>r;r++)n[r].onError(t);this.observers=[]}},onNext:function(t){e.call(this),this.isStopped||(this.value=t,this.hasValue=!0)},dispose:function(){this.isDisposed=!0,this.observers=null,this.exception=null,this.value=null}}),r}(_n),vr=function(t){function e(t){return this.observable.subscribe(t)}function n(n,r){t.call(this,e),this.observer=n,this.observable=r}return ze(n,t),Le(n.prototype,gn,{onCompleted:function(){this.observer.onCompleted()},onError:function(t){this.observer.onError(t)},onNext:function(t){this.observer.onNext(t)}}),n}(_n);"function"==typeof define&&"object"==typeof define.amd&&define.amd?(X.Rx=ee,define(function(){return ee})):Z&&G?Y?(G.exports=ee).Rx=ee:Z.Rx=ee:X.Rx=ee}).call(this); \ No newline at end of file diff --git a/ajax/libs/rxjs/2.2.28/rx.all.js b/ajax/libs/rxjs/2.2.28/rx.all.js new file mode 100644 index 000000000..4666fa4c2 --- /dev/null +++ b/ajax/libs/rxjs/2.2.28/rx.all.js @@ -0,0 +1,9235 @@ +// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. + +;(function (undefined) { + + var objectTypes = { + 'boolean': false, + 'function': true, + 'object': true, + 'number': false, + 'string': false, + 'undefined': false + }; + + var root = (objectTypes[typeof window] && window) || this, + freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports, + freeModule = objectTypes[typeof module] && module && !module.nodeType && module, + moduleExports = freeModule && freeModule.exports === freeExports && freeExports, + freeGlobal = objectTypes[typeof global] && global; + + if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal)) { + root = freeGlobal; + } + + var Rx = { + internals: {}, + config: { + Promise: root.Promise // Detect if promise exists + }, + helpers: { } + }; + + // Defaults + var noop = Rx.helpers.noop = function () { }, + identity = Rx.helpers.identity = function (x) { return x; }, + pluck = Rx.helpers.pluck = function (property) { return function (x) { return x[property]; }; }, + just = Rx.helpers.just = function (value) { return function () { return value; }; }, + defaultNow = Rx.helpers.defaultNow = Date.now, + defaultComparer = Rx.helpers.defaultComparer = function (x, y) { return isEqual(x, y); }, + defaultSubComparer = Rx.helpers.defaultSubComparer = function (x, y) { return x > y ? 1 : (x < y ? -1 : 0); }, + defaultKeySerializer = Rx.helpers.defaultKeySerializer = function (x) { return x.toString(); }, + defaultError = Rx.helpers.defaultError = function (err) { throw err; }, + isPromise = Rx.helpers.isPromise = function (p) { return !!p && typeof p.then === 'function' && p.then !== Rx.Observable.prototype.then; }, + asArray = Rx.helpers.asArray = function () { return Array.prototype.slice.call(arguments); }, + not = Rx.helpers.not = function (a) { return !a; }; + + // Errors + var sequenceContainsNoElements = 'Sequence contains no elements.'; + var argumentOutOfRange = 'Argument out of range'; + var objectDisposed = 'Object has been disposed'; + function checkDisposed() { if (this.isDisposed) { throw new Error(objectDisposed); } } + + // Shim in iterator support + var $iterator$ = (typeof Symbol === 'object' && Symbol.iterator) || + '_es6shim_iterator_'; + // Firefox ships a partial implementation using the name @@iterator. + // https://bugzilla.mozilla.org/show_bug.cgi?id=907077#c14 + // So use that name if we detect it. + if (root.Set && typeof new root.Set()['@@iterator'] === 'function') { + $iterator$ = '@@iterator'; + } + var doneEnumerator = { done: true, value: undefined }; + + /** `Object#toString` result shortcuts */ + var argsClass = '[object Arguments]', + arrayClass = '[object Array]', + boolClass = '[object Boolean]', + dateClass = '[object Date]', + errorClass = '[object Error]', + funcClass = '[object Function]', + numberClass = '[object Number]', + objectClass = '[object Object]', + regexpClass = '[object RegExp]', + stringClass = '[object String]'; + + var toString = Object.prototype.toString, + hasOwnProperty = Object.prototype.hasOwnProperty, + supportsArgsClass = toString.call(arguments) == argsClass, // For less -1); + } + }); + } + } + stackA.pop(); + stackB.pop(); + + return result; + } + var slice = Array.prototype.slice; + function argsOrArray(args, idx) { + return args.length === 1 && Array.isArray(args[idx]) ? + args[idx] : + slice.call(args); + } + var hasProp = {}.hasOwnProperty; + + /** @private */ + var inherits = this.inherits = Rx.internals.inherits = function (child, parent) { + function __() { this.constructor = child; } + __.prototype = parent.prototype; + child.prototype = new __(); + }; + + /** @private */ + var addProperties = Rx.internals.addProperties = function (obj) { + var sources = slice.call(arguments, 1); + for (var i = 0, len = sources.length; i < len; i++) { + var source = sources[i]; + for (var prop in source) { + obj[prop] = source[prop]; + } + } + }; + + // Rx Utils + var addRef = Rx.internals.addRef = function (xs, r) { + return new AnonymousObservable(function (observer) { + return new CompositeDisposable(r.getDisposable(), xs.subscribe(observer)); + }); + }; + + // Collection polyfills + function arrayInitialize(count, factory) { + var a = new Array(count); + for (var i = 0; i < count; i++) { + a[i] = factory(); + } + return a; + } + + // Collections + var IndexedItem = function (id, value) { + this.id = id; + this.value = value; + }; + + IndexedItem.prototype.compareTo = function (other) { + var c = this.value.compareTo(other.value); + if (c === 0) { + c = this.id - other.id; + } + return c; + }; + + // Priority Queue for Scheduling + var PriorityQueue = Rx.internals.PriorityQueue = function (capacity) { + this.items = new Array(capacity); + this.length = 0; + }; + + var priorityProto = PriorityQueue.prototype; + priorityProto.isHigherPriority = function (left, right) { + return this.items[left].compareTo(this.items[right]) < 0; + }; + + priorityProto.percolate = function (index) { + if (index >= this.length || index < 0) { + return; + } + var parent = index - 1 >> 1; + if (parent < 0 || parent === index) { + return; + } + if (this.isHigherPriority(index, parent)) { + var temp = this.items[index]; + this.items[index] = this.items[parent]; + this.items[parent] = temp; + this.percolate(parent); + } + }; + + priorityProto.heapify = function (index) { + if (index === undefined) { + index = 0; + } + if (index >= this.length || index < 0) { + return; + } + var left = 2 * index + 1, + right = 2 * index + 2, + first = index; + if (left < this.length && this.isHigherPriority(left, first)) { + first = left; + } + if (right < this.length && this.isHigherPriority(right, first)) { + first = right; + } + if (first !== index) { + var temp = this.items[index]; + this.items[index] = this.items[first]; + this.items[first] = temp; + this.heapify(first); + } + }; + + priorityProto.peek = function () { return this.items[0].value; }; + + priorityProto.removeAt = function (index) { + this.items[index] = this.items[--this.length]; + delete this.items[this.length]; + this.heapify(); + }; + + priorityProto.dequeue = function () { + var result = this.peek(); + this.removeAt(0); + return result; + }; + + priorityProto.enqueue = function (item) { + var index = this.length++; + this.items[index] = new IndexedItem(PriorityQueue.count++, item); + this.percolate(index); + }; + + priorityProto.remove = function (item) { + for (var i = 0; i < this.length; i++) { + if (this.items[i].value === item) { + this.removeAt(i); + return true; + } + } + return false; + }; + PriorityQueue.count = 0; + /** + * Represents a group of disposable resources that are disposed together. + * @constructor + */ + var CompositeDisposable = Rx.CompositeDisposable = function () { + this.disposables = argsOrArray(arguments, 0); + this.isDisposed = false; + this.length = this.disposables.length; + }; + + var CompositeDisposablePrototype = CompositeDisposable.prototype; + + /** + * Adds a disposable to the CompositeDisposable or disposes the disposable if the CompositeDisposable is disposed. + * @param {Mixed} item Disposable to add. + */ + CompositeDisposablePrototype.add = function (item) { + if (this.isDisposed) { + item.dispose(); + } else { + this.disposables.push(item); + this.length++; + } + }; + + /** + * Removes and disposes the first occurrence of a disposable from the CompositeDisposable. + * @param {Mixed} item Disposable to remove. + * @returns {Boolean} true if found; false otherwise. + */ + CompositeDisposablePrototype.remove = function (item) { + var shouldDispose = false; + if (!this.isDisposed) { + var idx = this.disposables.indexOf(item); + if (idx !== -1) { + shouldDispose = true; + this.disposables.splice(idx, 1); + this.length--; + item.dispose(); + } + + } + return shouldDispose; + }; + + /** + * Disposes all disposables in the group and removes them from the group. + */ + CompositeDisposablePrototype.dispose = function () { + if (!this.isDisposed) { + this.isDisposed = true; + var currentDisposables = this.disposables.slice(0); + this.disposables = []; + this.length = 0; + + for (var i = 0, len = currentDisposables.length; i < len; i++) { + currentDisposables[i].dispose(); + } + } + }; + + /** + * Removes and disposes all disposables from the CompositeDisposable, but does not dispose the CompositeDisposable. + */ + CompositeDisposablePrototype.clear = function () { + var currentDisposables = this.disposables.slice(0); + this.disposables = []; + this.length = 0; + for (var i = 0, len = currentDisposables.length; i < len; i++) { + currentDisposables[i].dispose(); + } + }; + + /** + * Determines whether the CompositeDisposable contains a specific disposable. + * @param {Mixed} item Disposable to search for. + * @returns {Boolean} true if the disposable was found; otherwise, false. + */ + CompositeDisposablePrototype.contains = function (item) { + return this.disposables.indexOf(item) !== -1; + }; + + /** + * Converts the existing CompositeDisposable to an array of disposables + * @returns {Array} An array of disposable objects. + */ + CompositeDisposablePrototype.toArray = function () { + return this.disposables.slice(0); + }; + + /** + * Provides a set of static methods for creating Disposables. + * + * @constructor + * @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once. + */ + var Disposable = Rx.Disposable = function (action) { + this.isDisposed = false; + this.action = action || noop; + }; + + /** Performs the task of cleaning up resources. */ + Disposable.prototype.dispose = function () { + if (!this.isDisposed) { + this.action(); + this.isDisposed = true; + } + }; + + /** + * Creates a disposable object that invokes the specified action when disposed. + * @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once. + * @return {Disposable} The disposable object that runs the given action upon disposal. + */ + var disposableCreate = Disposable.create = function (action) { return new Disposable(action); }; + + /** + * Gets the disposable that does nothing when disposed. + */ + var disposableEmpty = Disposable.empty = { dispose: noop }; + + var BooleanDisposable = (function () { + function BooleanDisposable (isSingle) { + this.isSingle = isSingle; + this.isDisposed = false; + this.current = null; + } + + var booleanDisposablePrototype = BooleanDisposable.prototype; + + /** + * Gets the underlying disposable. + * @return The underlying disposable. + */ + booleanDisposablePrototype.getDisposable = function () { + return this.current; + }; + + /** + * Sets the underlying disposable. + * @param {Disposable} value The new underlying disposable. + */ + booleanDisposablePrototype.setDisposable = function (value) { + if (this.current && this.isSingle) { + throw new Error('Disposable has already been assigned'); + } + + var shouldDispose = this.isDisposed, old; + if (!shouldDispose) { + old = this.current; + this.current = value; + } + if (old) { + old.dispose(); + } + if (shouldDispose && value) { + value.dispose(); + } + }; + + /** + * Disposes the underlying disposable as well as all future replacements. + */ + booleanDisposablePrototype.dispose = function () { + var old; + if (!this.isDisposed) { + this.isDisposed = true; + old = this.current; + this.current = null; + } + if (old) { + old.dispose(); + } + }; + + return BooleanDisposable; + }()); + + /** + * Represents a disposable resource which only allows a single assignment of its underlying disposable resource. + * If an underlying disposable resource has already been set, future attempts to set the underlying disposable resource will throw an Error. + */ + var SingleAssignmentDisposable = Rx.SingleAssignmentDisposable = (function (super_) { + inherits(SingleAssignmentDisposable, super_); + + function SingleAssignmentDisposable() { + super_.call(this, true); + } + + return SingleAssignmentDisposable; + }(BooleanDisposable)); + + /** + * Represents a disposable resource whose underlying disposable resource can be replaced by another disposable resource, causing automatic disposal of the previous underlying disposable resource. + */ + var SerialDisposable = Rx.SerialDisposable = (function (super_) { + inherits(SerialDisposable, super_); + + function SerialDisposable() { + super_.call(this, false); + } + + return SerialDisposable; + }(BooleanDisposable)); + + /** + * Represents a disposable resource that only disposes its underlying disposable resource when all dependent disposable objects have been disposed. + */ + var RefCountDisposable = Rx.RefCountDisposable = (function () { + + function InnerDisposable(disposable) { + this.disposable = disposable; + this.disposable.count++; + this.isInnerDisposed = false; + } + + InnerDisposable.prototype.dispose = function () { + if (!this.disposable.isDisposed) { + if (!this.isInnerDisposed) { + this.isInnerDisposed = true; + this.disposable.count--; + if (this.disposable.count === 0 && this.disposable.isPrimaryDisposed) { + this.disposable.isDisposed = true; + this.disposable.underlyingDisposable.dispose(); + } + } + } + }; + + /** + * Initializes a new instance of the RefCountDisposable with the specified disposable. + * @constructor + * @param {Disposable} disposable Underlying disposable. + */ + function RefCountDisposable(disposable) { + this.underlyingDisposable = disposable; + this.isDisposed = false; + this.isPrimaryDisposed = false; + this.count = 0; + } + + /** + * Disposes the underlying disposable only when all dependent disposables have been disposed + */ + RefCountDisposable.prototype.dispose = function () { + if (!this.isDisposed) { + if (!this.isPrimaryDisposed) { + this.isPrimaryDisposed = true; + if (this.count === 0) { + this.isDisposed = true; + this.underlyingDisposable.dispose(); + } + } + } + }; + + /** + * Returns a dependent disposable that when disposed decreases the refcount on the underlying disposable. + * @returns {Disposable} A dependent disposable contributing to the reference count that manages the underlying disposable's lifetime. + */ + RefCountDisposable.prototype.getDisposable = function () { + return this.isDisposed ? disposableEmpty : new InnerDisposable(this); + }; + + return RefCountDisposable; + })(); + + function ScheduledDisposable(scheduler, disposable) { + this.scheduler = scheduler; + this.disposable = disposable; + this.isDisposed = false; + } + + ScheduledDisposable.prototype.dispose = function () { + var parent = this; + this.scheduler.schedule(function () { + if (!parent.isDisposed) { + parent.isDisposed = true; + parent.disposable.dispose(); + } + }); + }; + + var ScheduledItem = Rx.internals.ScheduledItem = function (scheduler, state, action, dueTime, comparer) { + this.scheduler = scheduler; + this.state = state; + this.action = action; + this.dueTime = dueTime; + this.comparer = comparer || defaultSubComparer; + this.disposable = new SingleAssignmentDisposable(); + } + + ScheduledItem.prototype.invoke = function () { + this.disposable.setDisposable(this.invokeCore()); + }; + + ScheduledItem.prototype.compareTo = function (other) { + return this.comparer(this.dueTime, other.dueTime); + }; + + ScheduledItem.prototype.isCancelled = function () { + return this.disposable.isDisposed; + }; + + ScheduledItem.prototype.invokeCore = function () { + return this.action(this.scheduler, this.state); + }; + + /** Provides a set of static properties to access commonly used schedulers. */ + var Scheduler = Rx.Scheduler = (function () { + + /** + * @constructor + * @private + */ + function Scheduler(now, schedule, scheduleRelative, scheduleAbsolute) { + this.now = now; + this._schedule = schedule; + this._scheduleRelative = scheduleRelative; + this._scheduleAbsolute = scheduleAbsolute; + } + + function invokeRecImmediate(scheduler, pair) { + var state = pair.first, action = pair.second, group = new CompositeDisposable(), + recursiveAction = function (state1) { + action(state1, function (state2) { + var isAdded = false, isDone = false, + d = scheduler.scheduleWithState(state2, function (scheduler1, state3) { + if (isAdded) { + group.remove(d); + } else { + isDone = true; + } + recursiveAction(state3); + return disposableEmpty; + }); + if (!isDone) { + group.add(d); + isAdded = true; + } + }); + }; + recursiveAction(state); + return group; + } + + function invokeRecDate(scheduler, pair, method) { + var state = pair.first, action = pair.second, group = new CompositeDisposable(), + recursiveAction = function (state1) { + action(state1, function (state2, dueTime1) { + var isAdded = false, isDone = false, + d = scheduler[method].call(scheduler, state2, dueTime1, function (scheduler1, state3) { + if (isAdded) { + group.remove(d); + } else { + isDone = true; + } + recursiveAction(state3); + return disposableEmpty; + }); + if (!isDone) { + group.add(d); + isAdded = true; + } + }); + }; + recursiveAction(state); + return group; + } + + function invokeAction(scheduler, action) { + action(); + return disposableEmpty; + } + + var schedulerProto = Scheduler.prototype; + + /** + * Returns a scheduler that wraps the original scheduler, adding exception handling for scheduled actions. + * @param {Function} handler Handler that's run if an exception is caught. The exception will be rethrown if the handler returns false. + * @returns {Scheduler} Wrapper around the original scheduler, enforcing exception handling. + */ + schedulerProto.catchException = schedulerProto['catch'] = function (handler) { + return new CatchScheduler(this, handler); + }; + + /** + * Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation. + * @param {Number} period Period for running the work periodically. + * @param {Function} action Action to be executed. + * @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort). + */ + schedulerProto.schedulePeriodic = function (period, action) { + return this.schedulePeriodicWithState(null, period, function () { + action(); + }); + }; + + /** + * Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation. + * @param {Mixed} state Initial state passed to the action upon the first iteration. + * @param {Number} period Period for running the work periodically. + * @param {Function} action Action to be executed, potentially updating the state. + * @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort). + */ + schedulerProto.schedulePeriodicWithState = function (state, period, action) { + var s = state, id = setInterval(function () { + s = action(s); + }, period); + return disposableCreate(function () { + clearInterval(id); + }); + }; + + /** + * Schedules an action to be executed. + * @param {Function} action Action to execute. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.schedule = function (action) { + return this._schedule(action, invokeAction); + }; + + /** + * Schedules an action to be executed. + * @param state State passed to the action to be executed. + * @param {Function} action Action to be executed. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleWithState = function (state, action) { + return this._schedule(state, action); + }; + + /** + * Schedules an action to be executed after the specified relative due time. + * @param {Function} action Action to execute. + * @param {Number} dueTime Relative time after which to execute the action. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleWithRelative = function (dueTime, action) { + return this._scheduleRelative(action, dueTime, invokeAction); + }; + + /** + * Schedules an action to be executed after dueTime. + * @param state State passed to the action to be executed. + * @param {Function} action Action to be executed. + * @param {Number} dueTime Relative time after which to execute the action. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleWithRelativeAndState = function (state, dueTime, action) { + return this._scheduleRelative(state, dueTime, action); + }; + + /** + * Schedules an action to be executed at the specified absolute due time. + * @param {Function} action Action to execute. + * @param {Number} dueTime Absolute time at which to execute the action. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleWithAbsolute = function (dueTime, action) { + return this._scheduleAbsolute(action, dueTime, invokeAction); + }; + + /** + * Schedules an action to be executed at dueTime. + * @param {Mixed} state State passed to the action to be executed. + * @param {Function} action Action to be executed. + * @param {Number}dueTime Absolute time at which to execute the action. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleWithAbsoluteAndState = function (state, dueTime, action) { + return this._scheduleAbsolute(state, dueTime, action); + }; + + /** + * Schedules an action to be executed recursively. + * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleRecursive = function (action) { + return this.scheduleRecursiveWithState(action, function (_action, self) { + _action(function () { + self(_action); + }); + }); + }; + + /** + * Schedules an action to be executed recursively. + * @param {Mixed} state State passed to the action to be executed. + * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in recursive invocation state. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleRecursiveWithState = function (state, action) { + return this.scheduleWithState({ first: state, second: action }, function (s, p) { + return invokeRecImmediate(s, p); + }); + }; + + /** + * Schedules an action to be executed recursively after a specified relative due time. + * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified relative time. + * @param {Number}dueTime Relative time after which to execute the action for the first time. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleRecursiveWithRelative = function (dueTime, action) { + return this.scheduleRecursiveWithRelativeAndState(action, dueTime, function (_action, self) { + _action(function (dt) { + self(_action, dt); + }); + }); + }; + + /** + * Schedules an action to be executed recursively after a specified relative due time. + * @param {Mixed} state State passed to the action to be executed. + * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state. + * @param {Number}dueTime Relative time after which to execute the action for the first time. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleRecursiveWithRelativeAndState = function (state, dueTime, action) { + return this._scheduleRelative({ first: state, second: action }, dueTime, function (s, p) { + return invokeRecDate(s, p, 'scheduleWithRelativeAndState'); + }); + }; + + /** + * Schedules an action to be executed recursively at a specified absolute due time. + * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified absolute time. + * @param {Number}dueTime Absolute time at which to execute the action for the first time. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleRecursiveWithAbsolute = function (dueTime, action) { + return this.scheduleRecursiveWithAbsoluteAndState(action, dueTime, function (_action, self) { + _action(function (dt) { + self(_action, dt); + }); + }); + }; + + /** + * Schedules an action to be executed recursively at a specified absolute due time. + * @param {Mixed} state State passed to the action to be executed. + * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state. + * @param {Number}dueTime Absolute time at which to execute the action for the first time. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleRecursiveWithAbsoluteAndState = function (state, dueTime, action) { + return this._scheduleAbsolute({ first: state, second: action }, dueTime, function (s, p) { + return invokeRecDate(s, p, 'scheduleWithAbsoluteAndState'); + }); + }; + + /** Gets the current time according to the local machine's system clock. */ + Scheduler.now = defaultNow; + + /** + * Normalizes the specified TimeSpan value to a positive value. + * @param {Number} timeSpan The time span value to normalize. + * @returns {Number} The specified TimeSpan value if it is zero or positive; otherwise, 0 + */ + Scheduler.normalize = function (timeSpan) { + if (timeSpan < 0) { + timeSpan = 0; + } + return timeSpan; + }; + + return Scheduler; + }()); + + var normalizeTime = Scheduler.normalize; + + var SchedulePeriodicRecursive = Rx.internals.SchedulePeriodicRecursive = (function () { + function tick(command, recurse) { + recurse(0, this._period); + try { + this._state = this._action(this._state); + } catch (e) { + this._cancel.dispose(); + throw e; + } + } + + function SchedulePeriodicRecursive(scheduler, state, period, action) { + this._scheduler = scheduler; + this._state = state; + this._period = period; + this._action = action; + } + + SchedulePeriodicRecursive.prototype.start = function () { + var d = new SingleAssignmentDisposable(); + this._cancel = d; + d.setDisposable(this._scheduler.scheduleRecursiveWithRelativeAndState(0, this._period, tick.bind(this))); + + return d; + }; + + return SchedulePeriodicRecursive; + }()); + + /** + * Gets a scheduler that schedules work immediately on the current thread. + */ + var immediateScheduler = Scheduler.immediate = (function () { + + function scheduleNow(state, action) { return action(this, state); } + + function scheduleRelative(state, dueTime, action) { + var dt = normalizeTime(dt); + while (dt - this.now() > 0) { } + return action(this, state); + } + + function scheduleAbsolute(state, dueTime, action) { + return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); + } + + return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); + }()); + + /** + * Gets a scheduler that schedules work as soon as possible on the current thread. + */ + var currentThreadScheduler = Scheduler.currentThread = (function () { + var queue; + + function runTrampoline (q) { + var item; + while (q.length > 0) { + item = q.dequeue(); + if (!item.isCancelled()) { + // Note, do not schedule blocking work! + while (item.dueTime - Scheduler.now() > 0) { + } + if (!item.isCancelled()) { + item.invoke(); + } + } + } + } + + function scheduleNow(state, action) { + return this.scheduleWithRelativeAndState(state, 0, action); + } + + function scheduleRelative(state, dueTime, action) { + var dt = this.now() + Scheduler.normalize(dueTime), + si = new ScheduledItem(this, state, action, dt), + t; + if (!queue) { + queue = new PriorityQueue(4); + queue.enqueue(si); + try { + runTrampoline(queue); + } catch (e) { + throw e; + } finally { + queue = null; + } + } else { + queue.enqueue(si); + } + return si.disposable; + } + + function scheduleAbsolute(state, dueTime, action) { + return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); + } + + var currentScheduler = new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); + currentScheduler.scheduleRequired = function () { return queue === null; }; + currentScheduler.ensureTrampoline = function (action) { + if (queue === null) { + return this.schedule(action); + } else { + return action(); + } + }; + + return currentScheduler; + }()); + + + var scheduleMethod, clearMethod = noop; + (function () { + + var reNative = RegExp('^' + + String(toString) + .replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + .replace(/toString| for [^\]]+/g, '.*?') + '$' + ); + + var setImmediate = typeof (setImmediate = freeGlobal && moduleExports && freeGlobal.setImmediate) == 'function' && + !reNative.test(setImmediate) && setImmediate, + clearImmediate = typeof (clearImmediate = freeGlobal && moduleExports && freeGlobal.clearImmediate) == 'function' && + !reNative.test(clearImmediate) && clearImmediate; + + function postMessageSupported () { + // Ensure not in a worker + if (!root.postMessage || root.importScripts) { return false; } + var isAsync = false, + oldHandler = root.onmessage; + // Test for async + root.onmessage = function () { isAsync = true; }; + root.postMessage('','*'); + root.onmessage = oldHandler; + + return isAsync; + } + + // Use in order, nextTick, setImmediate, postMessage, MessageChannel, script readystatechanged, setTimeout + if (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]') { + scheduleMethod = process.nextTick; + } else if (typeof setImmediate === 'function') { + scheduleMethod = setImmediate; + clearMethod = clearImmediate; + } else if (postMessageSupported()) { + var MSG_PREFIX = 'ms.rx.schedule' + Math.random(), + tasks = {}, + taskId = 0; + + function onGlobalPostMessage(event) { + // Only if we're a match to avoid any other global events + if (typeof event.data === 'string' && event.data.substring(0, MSG_PREFIX.length) === MSG_PREFIX) { + var handleId = event.data.substring(MSG_PREFIX.length), + action = tasks[handleId]; + action(); + delete tasks[handleId]; + } + } + + if (root.addEventListener) { + root.addEventListener('message', onGlobalPostMessage, false); + } else { + root.attachEvent('onmessage', onGlobalPostMessage, false); + } + + scheduleMethod = function (action) { + var currentId = taskId++; + tasks[currentId] = action; + root.postMessage(MSG_PREFIX + currentId, '*'); + }; + } else if (!!root.MessageChannel) { + var channel = new root.MessageChannel(), + channelTasks = {}, + channelTaskId = 0; + + channel.port1.onmessage = function (event) { + var id = event.data, + action = channelTasks[id]; + action(); + delete channelTasks[id]; + }; + + scheduleMethod = function (action) { + var id = channelTaskId++; + channelTasks[id] = action; + channel.port2.postMessage(id); + }; + } else if ('document' in root && 'onreadystatechange' in root.document.createElement('script')) { + + scheduleMethod = function (action) { + var scriptElement = root.document.createElement('script'); + scriptElement.onreadystatechange = function () { + action(); + scriptElement.onreadystatechange = null; + scriptElement.parentNode.removeChild(scriptElement); + scriptElement = null; + }; + root.document.documentElement.appendChild(scriptElement); + }; + + } else { + scheduleMethod = function (action) { return setTimeout(action, 0); }; + clearMethod = clearTimeout; + } + }()); + + /** + * Gets a scheduler that schedules work via a timed callback based upon platform. + */ + var timeoutScheduler = Scheduler.timeout = (function () { + + function scheduleNow(state, action) { + var scheduler = this, + disposable = new SingleAssignmentDisposable(); + var id = scheduleMethod(function () { + if (!disposable.isDisposed) { + disposable.setDisposable(action(scheduler, state)); + } + }); + return new CompositeDisposable(disposable, disposableCreate(function () { + clearMethod(id); + })); + } + + function scheduleRelative(state, dueTime, action) { + var scheduler = this, + dt = Scheduler.normalize(dueTime); + if (dt === 0) { + return scheduler.scheduleWithState(state, action); + } + var disposable = new SingleAssignmentDisposable(); + var id = setTimeout(function () { + if (!disposable.isDisposed) { + disposable.setDisposable(action(scheduler, state)); + } + }, dt); + return new CompositeDisposable(disposable, disposableCreate(function () { + clearTimeout(id); + })); + } + + function scheduleAbsolute(state, dueTime, action) { + return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); + } + + return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); + })(); + + /** @private */ + var CatchScheduler = (function (_super) { + + function localNow() { + return this._scheduler.now(); + } + + function scheduleNow(state, action) { + return this._scheduler.scheduleWithState(state, this._wrap(action)); + } + + function scheduleRelative(state, dueTime, action) { + return this._scheduler.scheduleWithRelativeAndState(state, dueTime, this._wrap(action)); + } + + function scheduleAbsolute(state, dueTime, action) { + return this._scheduler.scheduleWithAbsoluteAndState(state, dueTime, this._wrap(action)); + } + + inherits(CatchScheduler, _super); + + /** @private */ + function CatchScheduler(scheduler, handler) { + this._scheduler = scheduler; + this._handler = handler; + this._recursiveOriginal = null; + this._recursiveWrapper = null; + _super.call(this, localNow, scheduleNow, scheduleRelative, scheduleAbsolute); + } + + /** @private */ + CatchScheduler.prototype._clone = function (scheduler) { + return new CatchScheduler(scheduler, this._handler); + }; + + /** @private */ + CatchScheduler.prototype._wrap = function (action) { + var parent = this; + return function (self, state) { + try { + return action(parent._getRecursiveWrapper(self), state); + } catch (e) { + if (!parent._handler(e)) { throw e; } + return disposableEmpty; + } + }; + }; + + /** @private */ + CatchScheduler.prototype._getRecursiveWrapper = function (scheduler) { + if (this._recursiveOriginal !== scheduler) { + this._recursiveOriginal = scheduler; + var wrapper = this._clone(scheduler); + wrapper._recursiveOriginal = scheduler; + wrapper._recursiveWrapper = wrapper; + this._recursiveWrapper = wrapper; + } + return this._recursiveWrapper; + }; + + /** @private */ + CatchScheduler.prototype.schedulePeriodicWithState = function (state, period, action) { + var self = this, failed = false, d = new SingleAssignmentDisposable(); + + d.setDisposable(this._scheduler.schedulePeriodicWithState(state, period, function (state1) { + if (failed) { return null; } + try { + return action(state1); + } catch (e) { + failed = true; + if (!self._handler(e)) { throw e; } + d.dispose(); + return null; + } + })); + + return d; + }; + + return CatchScheduler; + }(Scheduler)); + + /** + * Represents a notification to an observer. + */ + var Notification = Rx.Notification = (function () { + function Notification(kind, hasValue) { + this.hasValue = hasValue == null ? false : hasValue; + this.kind = kind; + } + + var NotificationPrototype = Notification.prototype; + + /** + * Invokes the delegate corresponding to the notification or the observer's method corresponding to the notification and returns the produced result. + * + * @memberOf Notification + * @param {Any} observerOrOnNext Delegate to invoke for an OnNext notification or Observer to invoke the notification on.. + * @param {Function} onError Delegate to invoke for an OnError notification. + * @param {Function} onCompleted Delegate to invoke for an OnCompleted notification. + * @returns {Any} Result produced by the observation. + */ + NotificationPrototype.accept = function (observerOrOnNext, onError, onCompleted) { + if (arguments.length === 1 && typeof observerOrOnNext === 'object') { + return this._acceptObservable(observerOrOnNext); + } + return this._accept(observerOrOnNext, onError, onCompleted); + }; + + /** + * Returns an observable sequence with a single notification. + * + * @memberOf Notification + * @param {Scheduler} [scheduler] Scheduler to send out the notification calls on. + * @returns {Observable} The observable sequence that surfaces the behavior of the notification upon subscription. + */ + NotificationPrototype.toObservable = function (scheduler) { + var notification = this; + scheduler || (scheduler = immediateScheduler); + return new AnonymousObservable(function (observer) { + return scheduler.schedule(function () { + notification._acceptObservable(observer); + if (notification.kind === 'N') { + observer.onCompleted(); + } + }); + }); + }; + + return Notification; + })(); + + /** + * Creates an object that represents an OnNext notification to an observer. + * @param {Any} value The value contained in the notification. + * @returns {Notification} The OnNext notification containing the value. + */ + var notificationCreateOnNext = Notification.createOnNext = (function () { + + function _accept (onNext) { + return onNext(this.value); + } + + function _acceptObservable(observer) { + return observer.onNext(this.value); + } + + function toString () { + return 'OnNext(' + this.value + ')'; + } + + return function (value) { + var notification = new Notification('N', true); + notification.value = value; + notification._accept = _accept; + notification._acceptObservable = _acceptObservable; + notification.toString = toString; + return notification; + }; + }()); + + /** + * Creates an object that represents an OnError notification to an observer. + * @param {Any} error The exception contained in the notification. + * @returns {Notification} The OnError notification containing the exception. + */ + var notificationCreateOnError = Notification.createOnError = (function () { + + function _accept (onNext, onError) { + return onError(this.exception); + } + + function _acceptObservable(observer) { + return observer.onError(this.exception); + } + + function toString () { + return 'OnError(' + this.exception + ')'; + } + + return function (exception) { + var notification = new Notification('E'); + notification.exception = exception; + notification._accept = _accept; + notification._acceptObservable = _acceptObservable; + notification.toString = toString; + return notification; + }; + }()); + + /** + * Creates an object that represents an OnCompleted notification to an observer. + * @returns {Notification} The OnCompleted notification. + */ + var notificationCreateOnCompleted = Notification.createOnCompleted = (function () { + + function _accept (onNext, onError, onCompleted) { + return onCompleted(); + } + + function _acceptObservable(observer) { + return observer.onCompleted(); + } + + function toString () { + return 'OnCompleted()'; + } + + return function () { + var notification = new Notification('C'); + notification._accept = _accept; + notification._acceptObservable = _acceptObservable; + notification.toString = toString; + return notification; + }; + }()); + + var Enumerator = Rx.internals.Enumerator = function (next) { + this._next = next; + }; + + Enumerator.prototype.next = function () { + return this._next(); + }; + + Enumerator.prototype[$iterator$] = function () { return this; } + + var Enumerable = Rx.internals.Enumerable = function (iterator) { + this._iterator = iterator; + }; + + Enumerable.prototype[$iterator$] = function () { + return this._iterator(); + }; + + Enumerable.prototype.concat = function () { + var sources = this; + return new AnonymousObservable(function (observer) { + var e; + try { + e = sources[$iterator$](); + } catch(err) { + observer.onError(); + return; + } + + var isDisposed, + subscription = new SerialDisposable(); + var cancelable = immediateScheduler.scheduleRecursive(function (self) { + var currentItem; + if (isDisposed) { return; } + + try { + currentItem = e.next(); + } catch (ex) { + observer.onError(ex); + return; + } + + if (currentItem.done) { + observer.onCompleted(); + return; + } + + // Check if promise + var currentValue = currentItem.value; + isPromise(currentValue) && (currentValue = observableFromPromise(currentValue)); + + var d = new SingleAssignmentDisposable(); + subscription.setDisposable(d); + d.setDisposable(currentValue.subscribe( + observer.onNext.bind(observer), + observer.onError.bind(observer), + function () { self(); }) + ); + }); + + return new CompositeDisposable(subscription, cancelable, disposableCreate(function () { + isDisposed = true; + })); + }); + }; + + Enumerable.prototype.catchException = function () { + var sources = this; + return new AnonymousObservable(function (observer) { + var e; + try { + e = sources[$iterator$](); + } catch(err) { + observer.onError(); + return; + } + + var isDisposed, + lastException, + subscription = new SerialDisposable(); + var cancelable = immediateScheduler.scheduleRecursive(function (self) { + if (isDisposed) { return; } + + var currentItem; + try { + currentItem = e.next(); + } catch (ex) { + observer.onError(ex); + return; + } + + if (currentItem.done) { + if (lastException) { + observer.onError(lastException); + } else { + observer.onCompleted(); + } + return; + } + + // Check if promise + var currentValue = currentItem.value; + isPromise(currentValue) && (currentValue = observableFromPromise(currentValue)); + + var d = new SingleAssignmentDisposable(); + subscription.setDisposable(d); + d.setDisposable(currentValue.subscribe( + observer.onNext.bind(observer), + function (exn) { + lastException = exn; + self(); + }, + observer.onCompleted.bind(observer))); + }); + return new CompositeDisposable(subscription, cancelable, disposableCreate(function () { + isDisposed = true; + })); + }); + }; + + var enumerableRepeat = Enumerable.repeat = function (value, repeatCount) { + if (repeatCount == null) { repeatCount = -1; } + return new Enumerable(function () { + var left = repeatCount; + return new Enumerator(function () { + if (left === 0) { return doneEnumerator; } + if (left > 0) { left--; } + return { done: false, value: value }; + }); + }); + }; + + var enumerableFor = Enumerable.forEach = function (source, selector, thisArg) { + selector || (selector = identity); + return new Enumerable(function () { + var index = -1; + return new Enumerator( + function () { + return ++index < source.length ? + { done: false, value: selector.call(thisArg, source[index], index, source) } : + doneEnumerator; + }); + }); + }; + + /** + * Supports push-style iteration over an observable sequence. + */ + var Observer = Rx.Observer = function () { }; + + /** + * Creates a notification callback from an observer. + * + * @param observer Observer object. + * @returns The action that forwards its input notification to the underlying observer. + */ + Observer.prototype.toNotifier = function () { + var observer = this; + return function (n) { + return n.accept(observer); + }; + }; + + /** + * Hides the identity of an observer. + + * @returns An observer that hides the identity of the specified observer. + */ + Observer.prototype.asObserver = function () { + return new AnonymousObserver(this.onNext.bind(this), this.onError.bind(this), this.onCompleted.bind(this)); + }; + + /** + * Checks access to the observer for grammar violations. This includes checking for multiple OnError or OnCompleted calls, as well as reentrancy in any of the observer methods. + * If a violation is detected, an Error is thrown from the offending observer method call. + * + * @returns An observer that checks callbacks invocations against the observer grammar and, if the checks pass, forwards those to the specified observer. + */ + Observer.prototype.checked = function () { return new CheckedObserver(this); }; + + /** + * Creates an observer from the specified OnNext, along with optional OnError, and OnCompleted actions. + * + * @static + * @memberOf Observer + * @param {Function} [onNext] Observer's OnNext action implementation. + * @param {Function} [onError] Observer's OnError action implementation. + * @param {Function} [onCompleted] Observer's OnCompleted action implementation. + * @returns {Observer} The observer object implemented using the given actions. + */ + var observerCreate = Observer.create = function (onNext, onError, onCompleted) { + onNext || (onNext = noop); + onError || (onError = defaultError); + onCompleted || (onCompleted = noop); + return new AnonymousObserver(onNext, onError, onCompleted); + }; + + /** + * Creates an observer from a notification callback. + * + * @static + * @memberOf Observer + * @param {Function} handler Action that handles a notification. + * @returns The observer object that invokes the specified handler using a notification corresponding to each message it receives. + */ + Observer.fromNotifier = function (handler) { + return new AnonymousObserver(function (x) { + return handler(notificationCreateOnNext(x)); + }, function (exception) { + return handler(notificationCreateOnError(exception)); + }, function () { + return handler(notificationCreateOnCompleted()); + }); + }; + + /** + * Schedules the invocation of observer methods on the given scheduler. + * @param {Scheduler} scheduler Scheduler to schedule observer messages on. + * @returns {Observer} Observer whose messages are scheduled on the given scheduler. + */ + Observer.notifyOn = function (scheduler) { + return new ObserveOnObserver(scheduler, this); + }; + + /** + * Abstract base class for implementations of the Observer class. + * This base class enforces the grammar of observers where OnError and OnCompleted are terminal messages. + */ + var AbstractObserver = Rx.internals.AbstractObserver = (function (_super) { + inherits(AbstractObserver, _super); + + /** + * Creates a new observer in a non-stopped state. + * + * @constructor + */ + function AbstractObserver() { + this.isStopped = false; + _super.call(this); + } + + /** + * Notifies the observer of a new element in the sequence. + * + * @memberOf AbstractObserver + * @param {Any} value Next element in the sequence. + */ + AbstractObserver.prototype.onNext = function (value) { + if (!this.isStopped) { + this.next(value); + } + }; + + /** + * Notifies the observer that an exception has occurred. + * + * @memberOf AbstractObserver + * @param {Any} error The error that has occurred. + */ + AbstractObserver.prototype.onError = function (error) { + if (!this.isStopped) { + this.isStopped = true; + this.error(error); + } + }; + + /** + * Notifies the observer of the end of the sequence. + */ + AbstractObserver.prototype.onCompleted = function () { + if (!this.isStopped) { + this.isStopped = true; + this.completed(); + } + }; + + /** + * Disposes the observer, causing it to transition to the stopped state. + */ + AbstractObserver.prototype.dispose = function () { + this.isStopped = true; + }; + + AbstractObserver.prototype.fail = function (e) { + if (!this.isStopped) { + this.isStopped = true; + this.error(e); + return true; + } + + return false; + }; + + return AbstractObserver; + }(Observer)); + + /** + * Class to create an Observer instance from delegate-based implementations of the on* methods. + */ + var AnonymousObserver = Rx.AnonymousObserver = (function (_super) { + inherits(AnonymousObserver, _super); + + /** + * Creates an observer from the specified OnNext, OnError, and OnCompleted actions. + * @param {Any} onNext Observer's OnNext action implementation. + * @param {Any} onError Observer's OnError action implementation. + * @param {Any} onCompleted Observer's OnCompleted action implementation. + */ + function AnonymousObserver(onNext, onError, onCompleted) { + _super.call(this); + this._onNext = onNext; + this._onError = onError; + this._onCompleted = onCompleted; + } + + /** + * Calls the onNext action. + * @param {Any} value Next element in the sequence. + */ + AnonymousObserver.prototype.next = function (value) { + this._onNext(value); + }; + + /** + * Calls the onError action. + * @param {Any} error The error that has occurred. + */ + AnonymousObserver.prototype.error = function (exception) { + this._onError(exception); + }; + + /** + * Calls the onCompleted action. + */ + AnonymousObserver.prototype.completed = function () { + this._onCompleted(); + }; + + return AnonymousObserver; + }(AbstractObserver)); + + var CheckedObserver = (function (_super) { + inherits(CheckedObserver, _super); + + function CheckedObserver(observer) { + _super.call(this); + this._observer = observer; + this._state = 0; // 0 - idle, 1 - busy, 2 - done + } + + var CheckedObserverPrototype = CheckedObserver.prototype; + + CheckedObserverPrototype.onNext = function (value) { + this.checkAccess(); + try { + this._observer.onNext(value); + } catch (e) { + throw e; + } finally { + this._state = 0; + } + }; + + CheckedObserverPrototype.onError = function (err) { + this.checkAccess(); + try { + this._observer.onError(err); + } catch (e) { + throw e; + } finally { + this._state = 2; + } + }; + + CheckedObserverPrototype.onCompleted = function () { + this.checkAccess(); + try { + this._observer.onCompleted(); + } catch (e) { + throw e; + } finally { + this._state = 2; + } + }; + + CheckedObserverPrototype.checkAccess = function () { + if (this._state === 1) { throw new Error('Re-entrancy detected'); } + if (this._state === 2) { throw new Error('Observer completed'); } + if (this._state === 0) { this._state = 1; } + }; + + return CheckedObserver; + }(Observer)); + + var ScheduledObserver = Rx.internals.ScheduledObserver = (function (_super) { + inherits(ScheduledObserver, _super); + + function ScheduledObserver(scheduler, observer) { + _super.call(this); + this.scheduler = scheduler; + this.observer = observer; + this.isAcquired = false; + this.hasFaulted = false; + this.queue = []; + this.disposable = new SerialDisposable(); + } + + ScheduledObserver.prototype.next = function (value) { + var self = this; + this.queue.push(function () { + self.observer.onNext(value); + }); + }; + + ScheduledObserver.prototype.error = function (exception) { + var self = this; + this.queue.push(function () { + self.observer.onError(exception); + }); + }; + + ScheduledObserver.prototype.completed = function () { + var self = this; + this.queue.push(function () { + self.observer.onCompleted(); + }); + }; + + ScheduledObserver.prototype.ensureActive = function () { + var isOwner = false, parent = this; + if (!this.hasFaulted && this.queue.length > 0) { + isOwner = !this.isAcquired; + this.isAcquired = true; + } + if (isOwner) { + this.disposable.setDisposable(this.scheduler.scheduleRecursive(function (self) { + var work; + if (parent.queue.length > 0) { + work = parent.queue.shift(); + } else { + parent.isAcquired = false; + return; + } + try { + work(); + } catch (ex) { + parent.queue = []; + parent.hasFaulted = true; + throw ex; + } + self(); + })); + } + }; + + ScheduledObserver.prototype.dispose = function () { + _super.prototype.dispose.call(this); + this.disposable.dispose(); + }; + + return ScheduledObserver; + }(AbstractObserver)); + + /** @private */ + var ObserveOnObserver = (function (_super) { + inherits(ObserveOnObserver, _super); + + /** @private */ + function ObserveOnObserver() { + _super.apply(this, arguments); + } + + /** @private */ + ObserveOnObserver.prototype.next = function (value) { + _super.prototype.next.call(this, value); + this.ensureActive(); + }; + + /** @private */ + ObserveOnObserver.prototype.error = function (e) { + _super.prototype.error.call(this, e); + this.ensureActive(); + }; + + /** @private */ + ObserveOnObserver.prototype.completed = function () { + _super.prototype.completed.call(this); + this.ensureActive(); + }; + + return ObserveOnObserver; + })(ScheduledObserver); + + var observableProto; + + /** + * Represents a push-style collection. + */ + var Observable = Rx.Observable = (function () { + + function Observable(subscribe) { + this._subscribe = subscribe; + } + + observableProto = Observable.prototype; + + /** + * Subscribes an observer to the observable sequence. + * + * @example + * 1 - source.subscribe(); + * 2 - source.subscribe(observer); + * 3 - source.subscribe(function (x) { console.log(x); }); + * 4 - source.subscribe(function (x) { console.log(x); }, function (err) { console.log(err); }); + * 5 - source.subscribe(function (x) { console.log(x); }, function (err) { console.log(err); }, function () { console.log('done'); }); + * @param {Mixed} [observerOrOnNext] The object that is to receive notifications or an action to invoke for each element in the observable sequence. + * @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence. + * @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence. + * @returns {Diposable} The source sequence whose subscriptions and unsubscriptions happen on the specified scheduler. + */ + observableProto.subscribe = observableProto.forEach = function (observerOrOnNext, onError, onCompleted) { + var subscriber = typeof observerOrOnNext === 'object' ? + observerOrOnNext : + observerCreate(observerOrOnNext, onError, onCompleted); + + return this._subscribe(subscriber); + }; + + return Observable; + })(); + + /** + * Wraps the source sequence in order to run its observer callbacks on the specified scheduler. + * + * This only invokes observer callbacks on a scheduler. In case the subscription and/or unsubscription actions have side-effects + * that require to be run on a scheduler, use subscribeOn. + * + * @param {Scheduler} scheduler Scheduler to notify observers on. + * @returns {Observable} The source sequence whose observations happen on the specified scheduler. + */ + observableProto.observeOn = function (scheduler) { + var source = this; + return new AnonymousObservable(function (observer) { + return source.subscribe(new ObserveOnObserver(scheduler, observer)); + }); + }; + + /** + * Wraps the source sequence in order to run its subscription and unsubscription logic on the specified scheduler. This operation is not commonly used; + * see the remarks section for more information on the distinction between subscribeOn and observeOn. + + * This only performs the side-effects of subscription and unsubscription on the specified scheduler. In order to invoke observer + * callbacks on a scheduler, use observeOn. + + * @param {Scheduler} scheduler Scheduler to perform subscription and unsubscription actions on. + * @returns {Observable} The source sequence whose subscriptions and unsubscriptions happen on the specified scheduler. + */ + observableProto.subscribeOn = function (scheduler) { + var source = this; + return new AnonymousObservable(function (observer) { + var m = new SingleAssignmentDisposable(), d = new SerialDisposable(); + d.setDisposable(m); + m.setDisposable(scheduler.schedule(function () { + d.setDisposable(new ScheduledDisposable(scheduler, source.subscribe(observer))); + })); + return d; + }); + }; + + /** + * Converts a Promise to an Observable sequence + * @param {Promise} An ES6 Compliant promise. + * @returns {Observable} An Observable sequence which wraps the existing promise success and failure. + */ + var observableFromPromise = Observable.fromPromise = function (promise) { + return new AnonymousObservable(function (observer) { + promise.then( + function (value) { + observer.onNext(value); + observer.onCompleted(); + }, + function (reason) { + observer.onError(reason); + }); + + return function () { + if (promise && promise.abort) { + promise.abort(); + } + } + }); + }; + /* + * Converts an existing observable sequence to an ES6 Compatible Promise + * @example + * var promise = Rx.Observable.return(42).toPromise(RSVP.Promise); + * + * // With config + * Rx.config.Promise = RSVP.Promise; + * var promise = Rx.Observable.return(42).toPromise(); + * @param {Function} [promiseCtor] The constructor of the promise. If not provided, it looks for it in Rx.config.Promise. + * @returns {Promise} An ES6 compatible promise with the last value from the observable sequence. + */ + observableProto.toPromise = function (promiseCtor) { + promiseCtor || (promiseCtor = Rx.config.Promise); + if (!promiseCtor) { + throw new Error('Promise type not provided nor in Rx.config.Promise'); + } + var source = this; + return new promiseCtor(function (resolve, reject) { + // No cancellation can be done + var value, hasValue = false; + source.subscribe(function (v) { + value = v; + hasValue = true; + }, function (err) { + reject(err); + }, function () { + if (hasValue) { + resolve(value); + } + }); + }); + }; + /** + * Creates a list from an observable sequence. + * @returns An observable sequence containing a single element with a list containing all the elements of the source sequence. + */ + observableProto.toArray = function () { + var self = this; + return new AnonymousObservable(function(observer) { + var arr = []; + return self.subscribe( + arr.push.bind(arr), + observer.onError.bind(observer), + function () { + observer.onNext(arr); + observer.onCompleted(); + }); + }); + }; + + /** + * Creates an observable sequence from a specified subscribe method implementation. + * + * @example + * var res = Rx.Observable.create(function (observer) { return function () { } ); + * var res = Rx.Observable.create(function (observer) { return Rx.Disposable.empty; } ); + * var res = Rx.Observable.create(function (observer) { } ); + * + * @param {Function} subscribe Implementation of the resulting observable sequence's subscribe method, returning a function that will be wrapped in a Disposable. + * @returns {Observable} The observable sequence with the specified implementation for the Subscribe method. + */ + Observable.create = Observable.createWithDisposable = function (subscribe) { + return new AnonymousObservable(subscribe); + }; + + /** + * Returns an observable sequence that invokes the specified factory function whenever a new observer subscribes. + * + * @example + * var res = Rx.Observable.defer(function () { return Rx.Observable.fromArray([1,2,3]); }); + * @param {Function} observableFactory Observable factory function to invoke for each observer that subscribes to the resulting sequence or Promise. + * @returns {Observable} An observable sequence whose observers trigger an invocation of the given observable factory function. + */ + var observableDefer = Observable.defer = function (observableFactory) { + return new AnonymousObservable(function (observer) { + var result; + try { + result = observableFactory(); + } catch (e) { + return observableThrow(e).subscribe(observer); + } + isPromise(result) && (result = observableFromPromise(result)); + return result.subscribe(observer); + }); + }; + + /** + * Returns an empty observable sequence, using the specified scheduler to send out the single OnCompleted message. + * + * @example + * var res = Rx.Observable.empty(); + * var res = Rx.Observable.empty(Rx.Scheduler.timeout); + * @param {Scheduler} [scheduler] Scheduler to send the termination call on. + * @returns {Observable} An observable sequence with no elements. + */ + var observableEmpty = Observable.empty = function (scheduler) { + scheduler || (scheduler = immediateScheduler); + return new AnonymousObservable(function (observer) { + return scheduler.schedule(function () { + observer.onCompleted(); + }); + }); + }; + + /** + * Converts an array to an observable sequence, using an optional scheduler to enumerate the array. + * + * @example + * var res = Rx.Observable.fromArray([1,2,3]); + * var res = Rx.Observable.fromArray([1,2,3], Rx.Scheduler.timeout); + * @param {Scheduler} [scheduler] Scheduler to run the enumeration of the input sequence on. + * @returns {Observable} The observable sequence whose elements are pulled from the given enumerable sequence. + */ + var observableFromArray = Observable.fromArray = function (array, scheduler) { + scheduler || (scheduler = currentThreadScheduler); + return new AnonymousObservable(function (observer) { + var count = 0, len = array.length; + return scheduler.scheduleRecursive(function (self) { + if (count < len) { + observer.onNext(array[count++]); + self(); + } else { + observer.onCompleted(); + } + }); + }); + }; + + /** + * Converts an iterable into an Observable sequence + * + * @example + * var res = Rx.Observable.fromIterable(new Map()); + * var res = Rx.Observable.fromIterable(new Set(), Rx.Scheduler.timeout); + * @param {Scheduler} [scheduler] Scheduler to run the enumeration of the input sequence on. + * @returns {Observable} The observable sequence whose elements are pulled from the given generator sequence. + */ + Observable.fromIterable = function (iterable, scheduler) { + scheduler || (scheduler = currentThreadScheduler); + return new AnonymousObservable(function (observer) { + var iterator; + try { + iterator = iterable[$iterator$](); + } catch (e) { + observer.onError(e); + return; + } + + return scheduler.scheduleRecursive(function (self) { + var next; + try { + next = iterator.next(); + } catch (err) { + observer.onError(err); + return; + } + + if (next.done) { + observer.onCompleted(); + } else { + observer.onNext(next.value); + self(); + } + }); + }); + }; + + /** + * 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) { + scheduler || (scheduler = currentThreadScheduler); + return new AnonymousObservable(function (observer) { + var first = true, state = initialState; + return scheduler.scheduleRecursive(function (self) { + var hasResult, result; + try { + if (first) { + first = false; + } else { + state = iterate(state); + } + hasResult = condition(state); + if (hasResult) { + result = resultSelector(state); + } + } catch (exception) { + observer.onError(exception); + return; + } + if (hasResult) { + observer.onNext(result); + self(); + } else { + observer.onCompleted(); + } + }); + }); + }; + + /** + * This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments. + * @example + * var res = Rx.Observable.of(1,2,3); + * @returns {Observable} The observable sequence whose elements are pulled from the given arguments. + */ + Observable.of = function () { + var len = arguments.length, args = new Array(len); + for(var i = 0; i < len; i++) { args[i] = arguments[i]; } + return observableFromArray(args); + }; + + /** + * This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments. + * @example + * var res = Rx.Observable.of(1,2,3); + * @param {Scheduler} scheduler A scheduler to use for scheduling the arguments. + * @returns {Observable} The observable sequence whose elements are pulled from the given arguments. + */ + var observableOf = Observable.ofWithScheduler = function (scheduler) { + var len = arguments.length - 1, args = new Array(len); + for(var i = 0; i < len; i++) { args[i] = arguments[i + 1]; } + return observableFromArray(args, scheduler); + }; + + /** + * Returns a non-terminating observable sequence, which can be used to denote an infinite duration (e.g. when using reactive joins). + * @returns {Observable} An observable sequence whose observers will never get called. + */ + var observableNever = Observable.never = function () { + return new AnonymousObservable(function () { + return disposableEmpty; + }); + }; + + /** + * Generates an observable sequence of integral numbers within a specified range, using the specified scheduler to send out observer messages. + * + * @example + * var res = Rx.Observable.range(0, 10); + * var res = Rx.Observable.range(0, 10, Rx.Scheduler.timeout); + * @param {Number} start The value of the first integer in the sequence. + * @param {Number} count The number of sequential integers to generate. + * @param {Scheduler} [scheduler] Scheduler to run the generator loop on. If not specified, defaults to Scheduler.currentThread. + * @returns {Observable} An observable sequence that contains a range of sequential integral numbers. + */ + Observable.range = function (start, count, scheduler) { + scheduler || (scheduler = currentThreadScheduler); + return new AnonymousObservable(function (observer) { + return scheduler.scheduleRecursiveWithState(0, function (i, self) { + if (i < count) { + observer.onNext(start + i); + self(i + 1); + } else { + observer.onCompleted(); + } + }); + }); + }; + + /** + * Generates an observable sequence that repeats the given element the specified number of times, using the specified scheduler to send out observer messages. + * + * @example + * var res = Rx.Observable.repeat(42); + * var res = Rx.Observable.repeat(42, 4); + * 3 - res = Rx.Observable.repeat(42, 4, Rx.Scheduler.timeout); + * 4 - res = Rx.Observable.repeat(42, null, Rx.Scheduler.timeout); + * @param {Mixed} value Element to repeat. + * @param {Number} repeatCount [Optiona] Number of times to repeat the element. If not specified, repeats indefinitely. + * @param {Scheduler} scheduler Scheduler to run the producer loop on. If not specified, defaults to Scheduler.immediate. + * @returns {Observable} An observable sequence that repeats the given element the specified number of times. + */ + Observable.repeat = function (value, repeatCount, scheduler) { + scheduler || (scheduler = currentThreadScheduler); + if (repeatCount == null) { + repeatCount = -1; + } + return observableReturn(value, scheduler).repeat(repeatCount); + }; + + /** + * Returns an observable sequence that contains a single element, using the specified scheduler to send out observer messages. + * There is an alias called 'just', and 'returnValue' for browsers 0) { + s = q.shift(); + subscribe(s); + } else { + activeCount--; + if (isStopped && activeCount === 0) { + observer.onCompleted(); + } + } + })); + }; + group.add(sources.subscribe(function (innerSource) { + if (activeCount < maxConcurrentOrOther) { + activeCount++; + subscribe(innerSource); + } else { + q.push(innerSource); + } + }, observer.onError.bind(observer), function () { + isStopped = true; + if (activeCount === 0) { + observer.onCompleted(); + } + })); + return group; + }); + }; + + /** + * Merges all the observable sequences into a single observable sequence. + * The scheduler is optional and if not specified, the immediate scheduler is used. + * + * @example + * 1 - merged = Rx.Observable.merge(xs, ys, zs); + * 2 - merged = Rx.Observable.merge([xs, ys, zs]); + * 3 - merged = Rx.Observable.merge(scheduler, xs, ys, zs); + * 4 - merged = Rx.Observable.merge(scheduler, [xs, ys, zs]); + * @returns {Observable} The observable sequence that merges the elements of the observable sequences. + */ + var observableMerge = Observable.merge = function () { + var scheduler, sources; + if (!arguments[0]) { + scheduler = immediateScheduler; + sources = slice.call(arguments, 1); + } else if (arguments[0].now) { + scheduler = arguments[0]; + sources = slice.call(arguments, 1); + } else { + scheduler = immediateScheduler; + sources = slice.call(arguments, 0); + } + if (Array.isArray(sources[0])) { + sources = sources[0]; + } + return observableFromArray(sources, scheduler).mergeObservable(); + }; + + /** + * Merges an observable sequence of observable sequences into an observable sequence. + * @returns {Observable} The observable sequence that merges the elements of the inner sequences. + */ + observableProto.mergeObservable = observableProto.mergeAll =function () { + var sources = this; + return new AnonymousObservable(function (observer) { + var group = new CompositeDisposable(), + isStopped = false, + m = new SingleAssignmentDisposable(); + + group.add(m); + m.setDisposable(sources.subscribe(function (innerSource) { + var innerSubscription = new SingleAssignmentDisposable(); + group.add(innerSubscription); + + // Check if Promise or Observable + if (isPromise(innerSource)) { + innerSource = observableFromPromise(innerSource); + } + + innerSubscription.setDisposable(innerSource.subscribe(function (x) { + observer.onNext(x); + }, observer.onError.bind(observer), function () { + group.remove(innerSubscription); + if (isStopped && group.length === 1) { observer.onCompleted(); } + })); + }, observer.onError.bind(observer), function () { + isStopped = true; + if (group.length === 1) { observer.onCompleted(); } + })); + return group; + }); + }; + + /** + * Continues an observable sequence that is terminated normally or by an exception with the next observable sequence. + * @param {Observable} second Second observable sequence used to produce results after the first sequence terminates. + * @returns {Observable} An observable sequence that concatenates the first and second sequence, even if the first sequence terminates exceptionally. + */ + observableProto.onErrorResumeNext = function (second) { + if (!second) { + throw new Error('Second observable is required'); + } + return onErrorResumeNext([this, second]); + }; + + /** + * Continues an observable sequence that is terminated normally or by an exception with the next observable sequence. + * + * @example + * 1 - res = Rx.Observable.onErrorResumeNext(xs, ys, zs); + * 1 - res = Rx.Observable.onErrorResumeNext([xs, ys, zs]); + * @returns {Observable} An observable sequence that concatenates the source sequences, even if a sequence terminates exceptionally. + */ + var onErrorResumeNext = Observable.onErrorResumeNext = function () { + var sources = argsOrArray(arguments, 0); + return new AnonymousObservable(function (observer) { + var pos = 0, subscription = new SerialDisposable(), + cancelable = immediateScheduler.scheduleRecursive(function (self) { + var current, d; + if (pos < sources.length) { + current = sources[pos++]; + isPromise(current) && (current = observableFromPromise(current)); + d = new SingleAssignmentDisposable(); + subscription.setDisposable(d); + d.setDisposable(current.subscribe(observer.onNext.bind(observer), function () { + self(); + }, function () { + self(); + })); + } else { + observer.onCompleted(); + } + }); + return new CompositeDisposable(subscription, cancelable); + }); + }; + + /** + * Returns the values from the source observable sequence only after the other observable sequence produces a value. + * @param {Observable | Promise} other The observable sequence or Promise that triggers propagation of elements of the source sequence. + * @returns {Observable} An observable sequence containing the elements of the source sequence starting from the point the other sequence triggered propagation. + */ + observableProto.skipUntil = function (other) { + var source = this; + return new AnonymousObservable(function (observer) { + var isOpen = false; + var disposables = new CompositeDisposable(source.subscribe(function (left) { + isOpen && observer.onNext(left); + }, observer.onError.bind(observer), function () { + isOpen && observer.onCompleted(); + })); + + isPromise(other) && (other = observableFromPromise(other)); + + var rightSubscription = new SingleAssignmentDisposable(); + disposables.add(rightSubscription); + rightSubscription.setDisposable(other.subscribe(function () { + isOpen = true; + rightSubscription.dispose(); + }, observer.onError.bind(observer), function () { + rightSubscription.dispose(); + })); + + return disposables; + }); + }; + + /** + * Transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence. + * @returns {Observable} The observable sequence that at any point in time produces the elements of the most recent inner observable sequence that has been received. + */ + observableProto['switch'] = observableProto.switchLatest = function () { + var sources = this; + return new AnonymousObservable(function (observer) { + var hasLatest = false, + innerSubscription = new SerialDisposable(), + isStopped = false, + latest = 0, + subscription = sources.subscribe(function (innerSource) { + var d = new SingleAssignmentDisposable(), id = ++latest; + hasLatest = true; + innerSubscription.setDisposable(d); + + // Check if Promise or Observable + if (isPromise(innerSource)) { + innerSource = observableFromPromise(innerSource); + } + + d.setDisposable(innerSource.subscribe(function (x) { + if (latest === id) { + observer.onNext(x); + } + }, function (e) { + if (latest === id) { + observer.onError(e); + } + }, function () { + if (latest === id) { + hasLatest = false; + if (isStopped) { + observer.onCompleted(); + } + } + })); + }, observer.onError.bind(observer), function () { + isStopped = true; + if (!hasLatest) { + observer.onCompleted(); + } + }); + return new CompositeDisposable(subscription, innerSubscription); + }); + }; + + /** + * Returns the values from the source observable sequence until the other observable sequence produces a value. + * @param {Observable | Promise} other Observable sequence or Promise that terminates propagation of elements of the source sequence. + * @returns {Observable} An observable sequence containing the elements of the source sequence up to the point the other sequence interrupted further propagation. + */ + observableProto.takeUntil = function (other) { + var source = this; + return new AnonymousObservable(function (observer) { + isPromise(other) && (other = observableFromPromise(other)); + return new CompositeDisposable( + source.subscribe(observer), + other.subscribe(observer.onCompleted.bind(observer), observer.onError.bind(observer), noop) + ); + }); + }; + + function zipArray(second, resultSelector) { + var first = this; + return new AnonymousObservable(function (observer) { + var index = 0, len = second.length; + return first.subscribe(function (left) { + if (index < len) { + var right = second[index++], result; + try { + result = resultSelector(left, right); + } catch (e) { + observer.onError(e); + return; + } + observer.onNext(result); + } else { + observer.onCompleted(); + } + }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); + }); + } + + /** + * Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences or an array have produced an element at a corresponding index. + * The last element in the arguments must be a function to invoke for each series of elements at corresponding indexes in the sources. + * + * @example + * 1 - res = obs1.zip(obs2, fn); + * 1 - res = x1.zip([1,2,3], fn); + * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + observableProto.zip = function () { + if (Array.isArray(arguments[0])) { + return zipArray.apply(this, arguments); + } + var parent = this, sources = slice.call(arguments), resultSelector = sources.pop(); + sources.unshift(parent); + return new AnonymousObservable(function (observer) { + var n = sources.length, + queues = arrayInitialize(n, function () { return []; }), + isDone = arrayInitialize(n, function () { return false; }); + + function next(i) { + var res, queuedValues; + if (queues.every(function (x) { return x.length > 0; })) { + try { + queuedValues = queues.map(function (x) { return x.shift(); }); + res = resultSelector.apply(parent, queuedValues); + } catch (ex) { + observer.onError(ex); + return; + } + observer.onNext(res); + } else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) { + observer.onCompleted(); + } + }; + + function done(i) { + isDone[i] = true; + if (isDone.every(function (x) { return x; })) { + observer.onCompleted(); + } + } + + var subscriptions = new Array(n); + for (var idx = 0; idx < n; idx++) { + (function (i) { + var source = sources[i], sad = new SingleAssignmentDisposable(); + isPromise(source) && (source = observableFromPromise(source)); + sad.setDisposable(source.subscribe(function (x) { + queues[i].push(x); + next(i); + }, observer.onError.bind(observer), function () { + done(i); + })); + subscriptions[i] = sad; + })(idx); + } + + return new CompositeDisposable(subscriptions); + }); + }; + /** + * Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index. + * @param arguments Observable sources. + * @param {Function} resultSelector Function to invoke for each series of elements at corresponding indexes in the sources. + * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + Observable.zip = function () { + var args = slice.call(arguments, 0), + first = args.shift(); + return first.zip.apply(first, args); + }; + + /** + * Merges the specified observable sequences into one observable sequence by emitting a list with the elements of the observable sequences at corresponding indexes. + * @param arguments Observable sources. + * @returns {Observable} An observable sequence containing lists of elements at corresponding indexes. + */ + Observable.zipArray = function () { + var sources = argsOrArray(arguments, 0); + return new AnonymousObservable(function (observer) { + var n = sources.length, + queues = arrayInitialize(n, function () { return []; }), + isDone = arrayInitialize(n, function () { return false; }); + + function next(i) { + if (queues.every(function (x) { return x.length > 0; })) { + var res = queues.map(function (x) { return x.shift(); }); + observer.onNext(res); + } else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) { + observer.onCompleted(); + return; + } + }; + + function done(i) { + isDone[i] = true; + if (isDone.every(identity)) { + observer.onCompleted(); + return; + } + } + + var subscriptions = new Array(n); + for (var idx = 0; idx < n; idx++) { + (function (i) { + subscriptions[i] = new SingleAssignmentDisposable(); + subscriptions[i].setDisposable(sources[i].subscribe(function (x) { + queues[i].push(x); + next(i); + }, observer.onError.bind(observer), function () { + done(i); + })); + })(idx); + } + + var compositeDisposable = new CompositeDisposable(subscriptions); + compositeDisposable.add(disposableCreate(function () { + for (var qIdx = 0, qLen = queues.length; qIdx < qLen; qIdx++) { + queues[qIdx] = []; + } + })); + return compositeDisposable; + }); + }; + + /** + * Hides the identity of an observable sequence. + * @returns {Observable} An observable sequence that hides the identity of the source sequence. + */ + observableProto.asObservable = function () { + var source = this; + return new AnonymousObservable(function (observer) { + return source.subscribe(observer); + }); + }; + + /** + * Projects each element of an observable sequence into zero or more buffers which are produced based on element count information. + * + * @example + * var res = xs.bufferWithCount(10); + * var res = xs.bufferWithCount(10, 1); + * @param {Number} count Length of each buffer. + * @param {Number} [skip] Number of elements to skip between creation of consecutive buffers. If not provided, defaults to the count. + * @returns {Observable} An observable sequence of buffers. + */ + observableProto.bufferWithCount = function (count, skip) { + if (typeof skip !== 'number') { + skip = count; + } + return this.windowWithCount(count, skip).selectMany(function (x) { + return x.toArray(); + }).where(function (x) { + return x.length > 0; + }); + }; + + /** + * Dematerializes the explicit notification values of an observable sequence as implicit notifications. + * @returns {Observable} An observable sequence exhibiting the behavior corresponding to the source sequence's notification values. + */ + observableProto.dematerialize = function () { + var source = this; + return new AnonymousObservable(function (observer) { + return source.subscribe(function (x) { + return x.accept(observer); + }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); + }); + }; + + /** + * Returns an observable sequence that contains only distinct contiguous elements according to the keySelector and the comparer. + * + * var obs = observable.distinctUntilChanged(); + * var obs = observable.distinctUntilChanged(function (x) { return x.id; }); + * var obs = observable.distinctUntilChanged(function (x) { return x.id; }, function (x, y) { return x === y; }); + * + * @param {Function} [keySelector] A function to compute the comparison key for each element. If not provided, it projects the value. + * @param {Function} [comparer] Equality comparer for computed key values. If not provided, defaults to an equality comparer function. + * @returns {Observable} An observable sequence only containing the distinct contiguous elements, based on a computed key value, from the source sequence. + */ + observableProto.distinctUntilChanged = function (keySelector, comparer) { + var source = this; + keySelector || (keySelector = identity); + comparer || (comparer = defaultComparer); + return new AnonymousObservable(function (observer) { + var hasCurrentKey = false, currentKey; + return source.subscribe(function (value) { + var comparerEquals = false, key; + try { + key = keySelector(value); + } catch (exception) { + observer.onError(exception); + return; + } + if (hasCurrentKey) { + try { + comparerEquals = comparer(currentKey, key); + } catch (exception) { + observer.onError(exception); + return; + } + } + if (!hasCurrentKey || !comparerEquals) { + hasCurrentKey = true; + currentKey = key; + observer.onNext(value); + } + }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); + }); + }; + + /** + * Invokes an action for each element in the observable sequence and invokes an action upon graceful or exceptional termination of the observable sequence. + * This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline. + * + * @example + * var res = observable.doAction(observer); + * var res = observable.doAction(onNext); + * var res = observable.doAction(onNext, onError); + * var res = observable.doAction(onNext, onError, onCompleted); + * @param {Mixed} observerOrOnNext Action to invoke for each element in the observable sequence or an observer. + * @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function. + * @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function. + * @returns {Observable} The source sequence with the side-effecting behavior applied. + */ + observableProto['do'] = observableProto.doAction = function (observerOrOnNext, onError, onCompleted) { + var source = this, onNextFunc; + if (typeof observerOrOnNext === 'function') { + onNextFunc = observerOrOnNext; + } else { + onNextFunc = observerOrOnNext.onNext.bind(observerOrOnNext); + onError = observerOrOnNext.onError.bind(observerOrOnNext); + onCompleted = observerOrOnNext.onCompleted.bind(observerOrOnNext); + } + return new AnonymousObservable(function (observer) { + return source.subscribe(function (x) { + try { + onNextFunc(x); + } catch (e) { + observer.onError(e); + } + observer.onNext(x); + }, function (exception) { + if (!onError) { + observer.onError(exception); + } else { + try { + onError(exception); + } catch (e) { + observer.onError(e); + } + observer.onError(exception); + } + }, function () { + if (!onCompleted) { + observer.onCompleted(); + } else { + try { + onCompleted(); + } catch (e) { + observer.onError(e); + } + observer.onCompleted(); + } + }); + }); + }; + + /** + * Invokes a specified action after the source observable sequence terminates gracefully or exceptionally. + * + * @example + * var res = observable.finallyAction(function () { console.log('sequence ended'; }); + * @param {Function} finallyAction Action to invoke after the source observable sequence terminates. + * @returns {Observable} Source sequence with the action-invoking termination behavior applied. + */ + observableProto['finally'] = observableProto.finallyAction = function (action) { + var source = this; + return new AnonymousObservable(function (observer) { + var subscription; + try { + subscription = source.subscribe(observer); + } catch (e) { + action(); + throw e; + } + return disposableCreate(function () { + try { + subscription.dispose(); + } catch (e) { + throw e; + } finally { + action(); + } + }); + }); + }; + + /** + * Ignores all elements in an observable sequence leaving only the termination messages. + * @returns {Observable} An empty observable sequence that signals termination, successful or exceptional, of the source sequence. + */ + observableProto.ignoreElements = function () { + var source = this; + return new AnonymousObservable(function (observer) { + return source.subscribe(noop, observer.onError.bind(observer), observer.onCompleted.bind(observer)); + }); + }; + + /** + * Materializes the implicit notifications of an observable sequence as explicit notification values. + * @returns {Observable} An observable sequence containing the materialized notification values from the source sequence. + */ + observableProto.materialize = function () { + var source = this; + return new AnonymousObservable(function (observer) { + return source.subscribe(function (value) { + observer.onNext(notificationCreateOnNext(value)); + }, function (e) { + observer.onNext(notificationCreateOnError(e)); + observer.onCompleted(); + }, function () { + observer.onNext(notificationCreateOnCompleted()); + observer.onCompleted(); + }); + }); + }; + + /** + * Repeats the observable sequence a specified number of times. If the repeat count is not specified, the sequence repeats indefinitely. + * + * @example + * var res = repeated = source.repeat(); + * var res = repeated = source.repeat(42); + * @param {Number} [repeatCount] Number of times to repeat the sequence. If not provided, repeats the sequence indefinitely. + * @returns {Observable} The observable sequence producing the elements of the given sequence repeatedly. + */ + observableProto.repeat = function (repeatCount) { + return enumerableRepeat(this, repeatCount).concat(); + }; + + /** + * Repeats the source observable sequence the specified number of times or until it successfully terminates. If the retry count is not specified, it retries indefinitely. + * + * @example + * var res = retried = retry.repeat(); + * var res = retried = retry.repeat(42); + * @param {Number} [retryCount] Number of times to retry the sequence. If not provided, retry the sequence indefinitely. + * @returns {Observable} An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully. + */ + observableProto.retry = function (retryCount) { + return enumerableRepeat(this, retryCount).catchException(); + }; + + /** + * Applies an accumulator function over an observable sequence and returns each intermediate result. The optional seed value is used as the initial accumulator value. + * For aggregation behavior with no intermediate results, see Observable.aggregate. + * @example + * var res = source.scan(function (acc, x) { return acc + x; }); + * var res = source.scan(0, function (acc, x) { return acc + x; }); + * @param {Mixed} [seed] The initial accumulator value. + * @param {Function} accumulator An accumulator function to be invoked on each element. + * @returns {Observable} An observable sequence containing the accumulated values. + */ + observableProto.scan = function () { + var hasSeed = false, seed, accumulator, source = this; + if (arguments.length === 2) { + hasSeed = true; + seed = arguments[0]; + accumulator = arguments[1]; + } else { + accumulator = arguments[0]; + } + return new AnonymousObservable(function (observer) { + var hasAccumulation, accumulation, hasValue; + return source.subscribe ( + function (x) { + try { + if (!hasValue) { + hasValue = true; + } + + if (hasAccumulation) { + accumulation = accumulator(accumulation, x); + } else { + accumulation = hasSeed ? accumulator(seed, x) : x; + hasAccumulation = true; + } + } catch (e) { + observer.onError(e); + return; + } + + observer.onNext(accumulation); + }, + observer.onError.bind(observer), + function () { + if (!hasValue && hasSeed) { + observer.onNext(seed); + } + observer.onCompleted(); + } + ); + }); + }; + + /** + * Bypasses a specified number of elements at the end of an observable sequence. + * @description + * This operator accumulates a queue with a length enough to store the first `count` elements. As more elements are + * received, elements are taken from the front of the queue and produced on the result sequence. This causes elements to be delayed. + * @param count Number of elements to bypass at the end of the source sequence. + * @returns {Observable} An observable sequence containing the source sequence elements except for the bypassed ones at the end. + */ + observableProto.skipLast = function (count) { + var source = this; + return new AnonymousObservable(function (observer) { + var q = []; + return source.subscribe(function (x) { + q.push(x); + if (q.length > count) { + observer.onNext(q.shift()); + } + }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); + }); + }; + + /** + * Prepends a sequence of values to an observable sequence with an optional scheduler and an argument list of values to prepend. + * + * var res = source.startWith(1, 2, 3); + * var res = source.startWith(Rx.Scheduler.timeout, 1, 2, 3); + * + * @memberOf Observable# + * @returns {Observable} The source sequence prepended with the specified values. + */ + observableProto.startWith = function () { + var values, scheduler, start = 0; + if (!!arguments.length && 'now' in Object(arguments[0])) { + scheduler = arguments[0]; + start = 1; + } else { + scheduler = immediateScheduler; + } + values = slice.call(arguments, start); + return enumerableFor([observableFromArray(values, scheduler), this]).concat(); + }; + + /** + * Returns a specified number of contiguous elements from the end of an observable sequence, using an optional scheduler to drain the queue. + * + * @example + * var res = source.takeLast(5); + * var res = source.takeLast(5, Rx.Scheduler.timeout); + * + * @description + * This operator accumulates a buffer with a length enough to store elements count elements. Upon completion of + * the source sequence, this buffer is drained on the result sequence. This causes the elements to be delayed. + * @param {Number} count Number of elements to take from the end of the source sequence. + * @param {Scheduler} [scheduler] Scheduler used to drain the queue upon completion of the source sequence. + * @returns {Observable} An observable sequence containing the specified number of elements from the end of the source sequence. + */ + observableProto.takeLast = function (count, scheduler) { + return this.takeLastBuffer(count).selectMany(function (xs) { return observableFromArray(xs, scheduler); }); + }; + + /** + * Returns an array with the specified number of contiguous elements from the end of an observable sequence. + * + * @description + * This operator accumulates a buffer with a length enough to store count elements. Upon completion of the + * source sequence, this buffer is produced on the result sequence. + * @param {Number} count Number of elements to take from the end of the source sequence. + * @returns {Observable} An observable sequence containing a single array with the specified number of elements from the end of the source sequence. + */ + observableProto.takeLastBuffer = function (count) { + var source = this; + return new AnonymousObservable(function (observer) { + var q = []; + return source.subscribe(function (x) { + q.push(x); + if (q.length > count) { + q.shift(); + } + }, observer.onError.bind(observer), function () { + observer.onNext(q); + observer.onCompleted(); + }); + }); + }; + + /** + * Projects each element of an observable sequence into zero or more windows which are produced based on element count information. + * + * var res = xs.windowWithCount(10); + * var res = xs.windowWithCount(10, 1); + * @param {Number} count Length of each window. + * @param {Number} [skip] Number of elements to skip between creation of consecutive windows. If not specified, defaults to the count. + * @returns {Observable} An observable sequence of windows. + */ + observableProto.windowWithCount = function (count, skip) { + var source = this; + if (count <= 0) { + throw new Error(argumentOutOfRange); + } + if (arguments.length === 1) { + skip = count; + } + if (skip <= 0) { + throw new Error(argumentOutOfRange); + } + return new AnonymousObservable(function (observer) { + var m = new SingleAssignmentDisposable(), + refCountDisposable = new RefCountDisposable(m), + n = 0, + q = [], + createWindow = function () { + var s = new Subject(); + q.push(s); + observer.onNext(addRef(s, refCountDisposable)); + }; + createWindow(); + m.setDisposable(source.subscribe(function (x) { + var s; + for (var i = 0, len = q.length; i < len; i++) { + q[i].onNext(x); + } + var c = n - count + 1; + if (c >= 0 && c % skip === 0) { + s = q.shift(); + s.onCompleted(); + } + n++; + if (n % skip === 0) { + createWindow(); + } + }, function (exception) { + while (q.length > 0) { + q.shift().onError(exception); + } + observer.onError(exception); + }, function () { + while (q.length > 0) { + q.shift().onCompleted(); + } + observer.onCompleted(); + })); + return refCountDisposable; + }); + }; + + function concatMap(selector) { + return this.map(function (x, i) { + var result = selector(x, i); + return isPromise(result) ? observableFromPromise(result) : result; + }).concatAll(); + } + + function concatMapObserver(onNext, onError, onCompleted) { + var source = this; + return new AnonymousObservable(function (observer) { + var index = 0; + + return source.subscribe( + function (x) { + observer.onNext(onNext(x, index++)); + }, + function (err) { + observer.onNext(onError(err)); + observer.completed(); + }, + function () { + observer.onNext(onCompleted()); + observer.onCompleted(); + }); + }).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.selectMany(function (x) { return Rx.Observable.range(0, x); }); + * Or: + * Projects each element of an observable sequence to an observable sequence, invokes the result selector for the source element and each of the corresponding inner sequence's elements, and merges the results into one observable sequence. + * + * var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); }, function (x, y) { return x + y; }); + * Or: + * Projects each element of the source observable sequence to the other observable sequence and merges the resulting observable sequences into one observable sequence. + * + * var res = source.selectMany(Rx.Observable.fromArray([1,2,3])); + * @param selector A transform function to apply to each element or an observable sequence to project each element from the + * source sequence onto which could be either an observable or Promise. + * @param {Function} [resultSelector] A transform function to apply to each element of the intermediate sequence. + * @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) { + if (resultSelector) { + return this.concatMap(function (x, i) { + var selectorResult = selector(x, i), + result = isPromise(selectorResult) ? observableFromPromise(selectorResult) : selectorResult; + + return result.map(function (y) { + return resultSelector(x, y, i); + }); + }); + } + if (typeof selector === 'function') { + return concatMap.call(this, selector); + } + return concatMap.call(this, function () { + return selector; + }); + }; + + /** + * Returns the elements of the specified sequence or the specified value in a singleton sequence if the sequence is empty. + * + * var res = obs = xs.defaultIfEmpty(); + * 2 - obs = xs.defaultIfEmpty(false); + * + * @memberOf Observable# + * @param defaultValue The value to return if the sequence is empty. If not provided, this defaults to null. + * @returns {Observable} An observable sequence that contains the specified default value if the source is empty; otherwise, the elements of the source itself. + */ + observableProto.defaultIfEmpty = function (defaultValue) { + var source = this; + if (defaultValue === undefined) { + defaultValue = null; + } + return new AnonymousObservable(function (observer) { + var found = false; + return source.subscribe(function (x) { + found = true; + observer.onNext(x); + }, observer.onError.bind(observer), function () { + if (!found) { + observer.onNext(defaultValue); + } + observer.onCompleted(); + }); + }); + }; + + /** + * Returns an observable sequence that contains only distinct elements according to the keySelector and the comparer. + * Usage of this operator should be considered carefully due to the maintenance of an internal lookup structure which can grow large. + * + * @example + * var res = obs = xs.distinct(); + * 2 - obs = xs.distinct(function (x) { return x.id; }); + * 2 - obs = xs.distinct(function (x) { return x.id; }, function (x) { return x.toString(); }); + * @param {Function} [keySelector] A function to compute the comparison key for each element. + * @param {Function} [keySerializer] Used to serialize the given object into a string for object comparison. + * @returns {Observable} An observable sequence only containing the distinct elements, based on a computed key value, from the source sequence. + */ + observableProto.distinct = function (keySelector, keySerializer) { + var source = this; + keySelector || (keySelector = identity); + keySerializer || (keySerializer = defaultKeySerializer); + return new AnonymousObservable(function (observer) { + var hashSet = {}; + return source.subscribe(function (x) { + var key, serializedKey, otherKey, hasMatch = false; + try { + key = keySelector(x); + serializedKey = keySerializer(key); + } catch (exception) { + observer.onError(exception); + return; + } + for (otherKey in hashSet) { + if (serializedKey === otherKey) { + hasMatch = true; + break; + } + } + if (!hasMatch) { + hashSet[serializedKey] = null; + observer.onNext(x); + } + }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); + }); + }; + + /** + * Groups the elements of an observable sequence according to a specified key selector function and comparer and selects the resulting elements by using a specified function. + * + * @example + * var res = observable.groupBy(function (x) { return x.id; }); + * 2 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }); + * 3 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }, function (x) { return x.toString(); }); + * @param {Function} keySelector A function to extract the key for each element. + * @param {Function} [elementSelector] A function to map each source element to an element in an observable group. + * @param {Function} [keySerializer] Used to serialize the given object into a string for object comparison. + * @returns {Observable} A sequence of observable groups, each of which corresponds to a unique key value, containing all elements that share that same key value. + */ + observableProto.groupBy = function (keySelector, elementSelector, keySerializer) { + return this.groupByUntil(keySelector, elementSelector, function () { + return observableNever(); + }, keySerializer); + }; + + /** + * Groups the elements of an observable sequence according to a specified key selector function. + * A duration selector function is used to control the lifetime of groups. When a group expires, it receives an OnCompleted notification. When a new element with the same + * key value as a reclaimed group occurs, the group will be reborn with a new lifetime request. + * + * @example + * var res = observable.groupByUntil(function (x) { return x.id; }, null, function () { return Rx.Observable.never(); }); + * 2 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }, function () { return Rx.Observable.never(); }); + * 3 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }, function () { return Rx.Observable.never(); }, function (x) { return x.toString(); }); + * @param {Function} keySelector A function to extract the key for each element. + * @param {Function} durationSelector A function to signal the expiration of a group. + * @param {Function} [keySerializer] Used to serialize the given object into a string for object comparison. + * @returns {Observable} + * A sequence of observable groups, each of which corresponds to a unique key value, containing all elements that share that same key value. + * If a group's lifetime expires, a new group with the same key value can be created once an element with such a key value is encoutered. + * + */ + observableProto.groupByUntil = function (keySelector, elementSelector, durationSelector, keySerializer) { + var source = this; + elementSelector || (elementSelector = identity); + keySerializer || (keySerializer = defaultKeySerializer); + return new AnonymousObservable(function (observer) { + var map = {}, + groupDisposable = new CompositeDisposable(), + refCountDisposable = new RefCountDisposable(groupDisposable); + groupDisposable.add(source.subscribe(function (x) { + var duration, durationGroup, element, fireNewMapEntry, group, key, serializedKey, md, writer, w; + try { + key = keySelector(x); + serializedKey = keySerializer(key); + } catch (e) { + for (w in map) { + map[w].onError(e); + } + observer.onError(e); + return; + } + fireNewMapEntry = false; + try { + writer = map[serializedKey]; + if (!writer) { + writer = new Subject(); + map[serializedKey] = writer; + fireNewMapEntry = true; + } + } catch (e) { + for (w in map) { + map[w].onError(e); + } + observer.onError(e); + return; + } + if (fireNewMapEntry) { + group = new GroupedObservable(key, writer, refCountDisposable); + durationGroup = new GroupedObservable(key, writer); + try { + duration = durationSelector(durationGroup); + } catch (e) { + for (w in map) { + map[w].onError(e); + } + observer.onError(e); + return; + } + observer.onNext(group); + md = new SingleAssignmentDisposable(); + groupDisposable.add(md); + var expire = function () { + if (serializedKey in map) { + delete map[serializedKey]; + writer.onCompleted(); + } + groupDisposable.remove(md); + }; + md.setDisposable(duration.take(1).subscribe(noop, function (exn) { + for (w in map) { + map[w].onError(exn); + } + observer.onError(exn); + }, function () { + expire(); + })); + } + try { + element = elementSelector(x); + } catch (e) { + for (w in map) { + map[w].onError(e); + } + observer.onError(e); + return; + } + writer.onNext(element); + }, function (ex) { + for (var w in map) { + map[w].onError(ex); + } + observer.onError(ex); + }, function () { + for (var w in map) { + map[w].onCompleted(); + } + observer.onCompleted(); + })); + return refCountDisposable; + }); + }; + + /** + * Projects each element of an observable sequence into a new form by incorporating the element's index. + * @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element. + * @param {Any} [thisArg] Object to use as this when executing callback. + * @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source. + */ + observableProto.select = observableProto.map = function (selector, thisArg) { + var parent = this; + return new AnonymousObservable(function (observer) { + var count = 0; + return parent.subscribe(function (value) { + var result; + try { + result = selector.call(thisArg, value, count++, parent); + } catch (exception) { + observer.onError(exception); + return; + } + observer.onNext(result); + }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); + }); + }; + + /** + * Retrieves the value of a specified property from all elements in the Observable sequence. + * @param {String} property The property to pluck. + * @returns {Observable} Returns a new Observable sequence of property values. + */ + observableProto.pluck = function (property) { + return this.select(function (x) { return x[property]; }); + }; + + function selectMany(selector) { + return this.select(function (x, i) { + var result = selector(x, i); + return isPromise(result) ? observableFromPromise(result) : result; + }).mergeObservable(); + } + + function selectManyObserver(onNext, onError, onCompleted) { + var source = this; + return new AnonymousObservable(function (observer) { + var index = 0; + + return source.subscribe( + function (x) { + observer.onNext(onNext(x, index++)); + }, + function (err) { + observer.onNext(onError(err)); + observer.completed(); + }, + function () { + observer.onNext(onCompleted()); + observer.onCompleted(); + }); + }).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 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.selectMany = observableProto.flatMap = function (selector, resultSelector) { + if (resultSelector) { + return this.selectMany(function (x, i) { + var selectorResult = selector(x, i), + result = isPromise(selectorResult) ? observableFromPromise(selectorResult) : selectorResult; + + return result.select(function (y) { + return resultSelector(x, y, i); + }); + }); + } + if (typeof selector === 'function') { + return selectMany.call(this, selector); + } + return selectMany.call(this, function () { + return selector; + }); + }; + + /** + * Projects each element of an observable sequence into a new sequence of observable sequences by incorporating the element's index and then + * transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence. + * @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element. + * @param {Any} [thisArg] Object to use as this when executing callback. + * @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source producing an Observable of Observable sequences + * and that at any point in time produces the elements of the most recent inner observable sequence that has been received. + */ + observableProto.selectSwitch = observableProto.flatMapLatest = observableProto.switchMap = function (selector, thisArg) { + return this.select(selector, thisArg).switchLatest(); + }; + + /** + * Bypasses a specified number of elements in an observable sequence and then returns the remaining elements. + * @param {Number} count The number of elements to skip before returning the remaining elements. + * @returns {Observable} An observable sequence that contains the elements that occur after the specified index in the input sequence. + */ + observableProto.skip = function (count) { + if (count < 0) { + throw new Error(argumentOutOfRange); + } + var observable = this; + return new AnonymousObservable(function (observer) { + var remaining = count; + return observable.subscribe(function (x) { + if (remaining <= 0) { + observer.onNext(x); + } else { + remaining--; + } + }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); + }); + }; + + /** + * Bypasses elements in an observable sequence as long as a specified condition is true and then returns the remaining elements. + * The element's index is used in the logic of the predicate function. + * + * var res = source.skipWhile(function (value) { return value < 10; }); + * var res = source.skipWhile(function (value, index) { return value < 10 || index < 10; }); + * @param {Function} predicate A function to test each element for a condition; the second parameter of the function represents the index of the source element. + * @param {Any} [thisArg] Object to use as this when executing callback. + * @returns {Observable} An observable sequence that contains the elements from the input sequence starting at the first element in the linear series that does not pass the test specified by predicate. + */ + observableProto.skipWhile = function (predicate, thisArg) { + var source = this; + return new AnonymousObservable(function (observer) { + var i = 0, running = false; + return source.subscribe(function (x) { + if (!running) { + try { + running = !predicate.call(thisArg, x, i++, source); + } catch (e) { + observer.onError(e); + return; + } + } + if (running) { + observer.onNext(x); + } + }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); + }); + }; + + /** + * Returns a specified number of contiguous elements from the start of an observable sequence, using the specified scheduler for the edge case of take(0). + * + * var res = source.take(5); + * var res = source.take(0, Rx.Scheduler.timeout); + * @param {Number} count The number of elements to return. + * @param {Scheduler} [scheduler] Scheduler used to produce an OnCompleted message in case 0; + }, + /** + * Notifies all subscribed observers about the end of the sequence. + */ + onCompleted: function () { + checkDisposed.call(this); + if (!this.isStopped) { + var os = this.observers.slice(0); + this.isStopped = true; + for (var i = 0, len = os.length; i < len; i++) { + os[i].onCompleted(); + } + + this.observers = []; + } + }, + /** + * Notifies all subscribed observers about the exception. + * @param {Mixed} error The exception to send to all observers. + */ + onError: function (error) { + checkDisposed.call(this); + if (!this.isStopped) { + var os = this.observers.slice(0); + this.isStopped = true; + this.exception = error; + + for (var i = 0, len = os.length; i < len; i++) { + os[i].onError(error); + } + + this.observers = []; + } + }, + /** + * Notifies all subscribed observers about the arrival of the specified element in the sequence. + * @param {Mixed} value The value to send to all observers. + */ + onNext: function (value) { + checkDisposed.call(this); + if (!this.isStopped) { + this.value = value; + var os = this.observers.slice(0); + for (var i = 0, len = os.length; i < len; i++) { + os[i].onNext(value); + } + } + }, + /** + * Unsubscribe all observers and release resources. + */ + dispose: function () { + this.isDisposed = true; + this.observers = null; + this.value = null; + this.exception = null; + } + }); + + return BehaviorSubject; + }(Observable)); + + /** + * Represents an object that is both an observable sequence as well as an observer. + * Each notification is broadcasted to all subscribed and future observers, subject to buffer trimming policies. + */ + var ReplaySubject = Rx.ReplaySubject = (function (_super) { + + function RemovableDisposable (subject, observer) { + this.subject = subject; + this.observer = observer; + }; + + RemovableDisposable.prototype.dispose = function () { + this.observer.dispose(); + if (!this.subject.isDisposed) { + var idx = this.subject.observers.indexOf(this.observer); + this.subject.observers.splice(idx, 1); + } + }; + + function subscribe(observer) { + var so = new ScheduledObserver(this.scheduler, observer), + subscription = new RemovableDisposable(this, so); + checkDisposed.call(this); + this._trim(this.scheduler.now()); + this.observers.push(so); + + var n = this.q.length; + + for (var i = 0, len = this.q.length; i < len; i++) { + so.onNext(this.q[i].value); + } + + if (this.hasError) { + n++; + so.onError(this.error); + } else if (this.isStopped) { + n++; + so.onCompleted(); + } + + so.ensureActive(n); + return subscription; + } + + inherits(ReplaySubject, _super); + + /** + * Initializes a new instance of the ReplaySubject class with the specified buffer size, window size and scheduler. + * @param {Number} [bufferSize] Maximum element count of the replay buffer. + * @param {Number} [windowSize] Maximum time length of the replay buffer. + * @param {Scheduler} [scheduler] Scheduler the observers are invoked on. + */ + function ReplaySubject(bufferSize, windowSize, scheduler) { + this.bufferSize = bufferSize == null ? Number.MAX_VALUE : bufferSize; + this.windowSize = windowSize == null ? Number.MAX_VALUE : windowSize; + this.scheduler = scheduler || currentThreadScheduler; + this.q = []; + this.observers = []; + this.isStopped = false; + this.isDisposed = false; + this.hasError = false; + this.error = null; + _super.call(this, subscribe); + } + + addProperties(ReplaySubject.prototype, Observer, { + /** + * Indicates whether the subject has observers subscribed to it. + * @returns {Boolean} Indicates whether the subject has observers subscribed to it. + */ + hasObservers: function () { + return this.observers.length > 0; + }, + /* @private */ + _trim: function (now) { + while (this.q.length > this.bufferSize) { + this.q.shift(); + } + while (this.q.length > 0 && (now - this.q[0].interval) > this.windowSize) { + this.q.shift(); + } + }, + /** + * Notifies all subscribed observers about the arrival of the specified element in the sequence. + * @param {Mixed} value The value to send to all observers. + */ + onNext: function (value) { + var observer; + checkDisposed.call(this); + if (!this.isStopped) { + var now = this.scheduler.now(); + this.q.push({ interval: now, value: value }); + this._trim(now); + + var o = this.observers.slice(0); + for (var i = 0, len = o.length; i < len; i++) { + observer = o[i]; + observer.onNext(value); + observer.ensureActive(); + } + } + }, + /** + * Notifies all subscribed observers about the exception. + * @param {Mixed} error The exception to send to all observers. + */ + onError: function (error) { + var observer; + checkDisposed.call(this); + if (!this.isStopped) { + this.isStopped = true; + this.error = error; + this.hasError = true; + var now = this.scheduler.now(); + this._trim(now); + var o = this.observers.slice(0); + for (var i = 0, len = o.length; i < len; i++) { + observer = o[i]; + observer.onError(error); + observer.ensureActive(); + } + this.observers = []; + } + }, + /** + * Notifies all subscribed observers about the end of the sequence. + */ + onCompleted: function () { + var observer; + checkDisposed.call(this); + if (!this.isStopped) { + this.isStopped = true; + var now = this.scheduler.now(); + this._trim(now); + var o = this.observers.slice(0); + for (var i = 0, len = o.length; i < len; i++) { + observer = o[i]; + observer.onCompleted(); + observer.ensureActive(); + } + this.observers = []; + } + }, + /** + * Unsubscribe all observers and release resources. + */ + dispose: function () { + this.isDisposed = true; + this.observers = null; + } + }); + + return ReplaySubject; + }(Observable)); + + /** @private */ + var ConnectableObservable = Rx.ConnectableObservable = (function (_super) { + inherits(ConnectableObservable, _super); + + /** + * @constructor + * @private + */ + function ConnectableObservable(source, subject) { + var state = { + subject: subject, + source: source.asObservable(), + hasSubscription: false, + subscription: null + }; + + this.connect = function () { + if (!state.hasSubscription) { + state.hasSubscription = true; + state.subscription = new CompositeDisposable(state.source.subscribe(state.subject), disposableCreate(function () { + state.hasSubscription = false; + })); + } + return state.subscription; + }; + + function subscribe(observer) { + return state.subject.subscribe(observer); + } + + _super.call(this, subscribe); + } + + /** + * @private + * @memberOf ConnectableObservable + */ + ConnectableObservable.prototype.connect = function () { return this.connect(); }; + + /** + * @private + * @memberOf ConnectableObservable + */ + ConnectableObservable.prototype.refCount = function () { + var connectableSubscription = null, count = 0, source = this; + return new AnonymousObservable(function (observer) { + var shouldConnect, subscription; + count++; + shouldConnect = count === 1; + subscription = source.subscribe(observer); + if (shouldConnect) { + connectableSubscription = source.connect(); + } + return disposableCreate(function () { + subscription.dispose(); + count--; + if (count === 0) { + connectableSubscription.dispose(); + } + }); + }); + }; + + return ConnectableObservable; + }(Observable)); + + // Real Dictionary + 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]; + var noSuchkey = "no such key"; + var 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 obj.getTime(); + } + + if (obj.getHashCode) { + return obj.getHashCode(); + } + + var id = 17 * uniqueIdCounter++; + obj.getHashCode = function () { return id; }; + return id; + }; + } ()); + + function newEntry() { + return { key: null, value: null, next: 0, hashCode: 0 }; + } + + // Dictionary implementation + + var Dictionary = function (capacity, comparer) { + if (capacity < 0) { + throw new Error('out of range') + } + if (capacity > 0) { + this._initialize(capacity); + } + + this.comparer = comparer || defaultComparer; + this.freeCount = 0; + this.size = 0; + this.freeList = -1; + }; + + Dictionary.prototype._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; + }; + Dictionary.prototype.count = function () { + return this.size; + }; + Dictionary.prototype.add = function (key, value) { + return this._insert(key, value, true); + }; + Dictionary.prototype._insert = function (key, value, add) { + if (!this.buckets) { + this._initialize(0); + } + var index3; + var num = getHashCode(key) & 2147483647; + var 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; + }; + + Dictionary.prototype._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; + }; + + Dictionary.prototype.remove = function (key) { + if (this.buckets) { + var num = getHashCode(key) & 2147483647; + var index1 = num % this.buckets.length; + var 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; + }; + + Dictionary.prototype.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; + }; + + Dictionary.prototype._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; + }; + + Dictionary.prototype.count = function () { + return this.size - this.freeCount; + }; + + Dictionary.prototype.tryGetValue = function (key) { + var entry = this._findEntry(key); + if (entry >= 0) { + return this.entries[entry].value; + } + return undefined; + }; + + Dictionary.prototype.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; + }; + + Dictionary.prototype.get = function (key) { + var entry = this._findEntry(key); + if (entry >= 0) { + return this.entries[entry].value; + } + throw new Error(noSuchkey); + }; + + Dictionary.prototype.set = function (key, value) { + this._insert(key, value, false); + }; + + Dictionary.prototype.containskey = function (key) { + return this._findEntry(key) >= 0; + }; + + /** + * 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(), + leftDone = false, + leftId = 0, + leftMap = new Dictionary(), + rightDone = false, + rightId = 0, + rightMap = new Dictionary(); + group.add(left.subscribe(function (value) { + var duration, + expire, + id = leftId++, + md = new SingleAssignmentDisposable(), + result, + values; + leftMap.add(id, value); + group.add(md); + expire = function () { + if (leftMap.remove(id) && leftMap.count() === 0 && leftDone) { + observer.onCompleted(); + } + return group.remove(md); + }; + try { + duration = leftDurationSelector(value); + } catch (e) { + observer.onError(e); + return; + } + md.setDisposable(duration.take(1).subscribe(noop, observer.onError.bind(observer), function () { expire(); })); + values = rightMap.getValues(); + for (var i = 0; i < values.length; i++) { + try { + result = resultSelector(value, values[i]); + } catch (exception) { + observer.onError(exception); + return; + } + observer.onNext(result); + } + }, observer.onError.bind(observer), function () { + leftDone = true; + if (rightDone || leftMap.count() === 0) { + observer.onCompleted(); + } + })); + group.add(right.subscribe(function (value) { + var duration, + expire, + id = rightId++, + md = new SingleAssignmentDisposable(), + result, + values; + rightMap.add(id, value); + group.add(md); + expire = function () { + if (rightMap.remove(id) && rightMap.count() === 0 && rightDone) { + observer.onCompleted(); + } + return group.remove(md); + }; + try { + duration = rightDurationSelector(value); + } catch (exception) { + observer.onError(exception); + return; + } + md.setDisposable(duration.take(1).subscribe(noop, observer.onError.bind(observer), function () { expire(); })); + values = leftMap.getValues(); + for (var i = 0; i < values.length; i++) { + try { + result = resultSelector(values[i], value); + } catch (exception) { + observer.onError(exception); + return; + } + observer.onNext(result); + } + }, observer.onError.bind(observer), function () { + rightDone = true; + if (leftDone || rightMap.count() === 0) { + observer.onCompleted(); + } + })); + return group; + }); + }; + + /** + * Correlates the elements of two sequences based on overlapping durations, and groups the results. + * + * @param {Observable} right The right observable sequence to join elements for. + * @param {Function} leftDurationSelector A function to select the duration (expressed as an observable sequence) of each element of the left observable sequence, used to determine overlap. + * @param {Function} rightDurationSelector A function to select the duration (expressed as an observable sequence) of each element of the right observable sequence, used to determine overlap. + * @param {Function} resultSelector A function invoked to compute a result element for any element of the left sequence with overlapping elements from the right observable sequence. The first parameter passed to the function is an element of the left sequence. The second parameter passed to the function is an observable sequence with elements from the right sequence that overlap with the left sequence's element. + * @returns {Observable} An observable sequence that contains result elements computed from source elements that have an overlapping duration. + */ + observableProto.groupJoin = function (right, leftDurationSelector, rightDurationSelector, resultSelector) { + var left = this; + return new AnonymousObservable(function (observer) { + var nothing = function () {}; + var group = new CompositeDisposable(); + var r = new RefCountDisposable(group); + var leftMap = new Dictionary(); + var rightMap = new Dictionary(); + var leftID = 0; + var rightID = 0; + + group.add(left.subscribe( + function (value) { + var s = new Subject(); + var id = leftID++; + leftMap.add(id, s); + var i, len, leftValues, rightValues; + + var result; + try { + result = resultSelector(value, addRef(s, r)); + } catch (e) { + leftValues = leftMap.getValues(); + for (i = 0, len = leftValues.length; i < len; i++) { + leftValues[i].onError(e); + } + observer.onError(e); + return; + } + observer.onNext(result); + + rightValues = rightMap.getValues(); + for (i = 0, len = rightValues.length; i < len; i++) { + s.onNext(rightValues[i]); + } + + var md = new SingleAssignmentDisposable(); + group.add(md); + + var expire = function () { + if (leftMap.remove(id)) { + s.onCompleted(); + } + + group.remove(md); + }; + + var duration; + try { + duration = leftDurationSelector(value); + } catch (e) { + leftValues = leftMap.getValues(); + for (i = 0, len = leftMap.length; i < len; i++) { + leftValues[i].onError(e); + } + observer.onError(e); + return; + } + + md.setDisposable(duration.take(1).subscribe( + nothing, + function (e) { + leftValues = leftMap.getValues(); + for (i = 0, len = leftValues.length; i < len; i++) { + leftValues[i].onError(e); + } + observer.onError(e); + }, + expire) + ); + }, + function (e) { + var leftValues = leftMap.getValues(); + for (var i = 0, len = leftValues.length; i < len; i++) { + leftValues[i].onError(e); + } + observer.onError(e); + }, + observer.onCompleted.bind(observer))); + + group.add(right.subscribe( + function (value) { + var leftValues, i, len; + 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) { + leftValues = leftMap.getValues(); + for (i = 0, len = leftMap.length; i < len; i++) { + leftValues[i].onError(e); + } + observer.onError(e); + return; + } + md.setDisposable(duration.take(1).subscribe( + nothing, + function (e) { + leftValues = leftMap.getValues(); + for (i = 0, len = leftMap.length; i < len; i++) { + leftValues[i].onError(e); + } + observer.onError(e); + }, + expire) + ); + + leftValues = leftMap.getValues(); + for (i = 0, len = leftValues.length; i < len; i++) { + leftValues[i].onNext(value); + } + }, + function (e) { + var leftValues = leftMap.getValues(); + for (var i = 0, len = leftValues.length; i < len; i++) { + leftValues[i].onError(e); + } + observer.onError(e); + })); + + return r; + }); + }; + + /** + * Projects each element of an observable sequence into zero or more buffers. + * + * @param {Mixed} bufferOpeningsOrClosingSelector Observable sequence whose elements denote the creation of new windows, or, a function invoked to define the boundaries of the produced windows (a new window is started when the previous one is closed, resulting in non-overlapping windows). + * @param {Function} [bufferClosingSelector] A function invoked to define the closing of each produced window. If a closing selector function is specified for the first parameter, this parameter is ignored. + * @returns {Observable} An observable sequence of windows. + */ + observableProto.buffer = function (bufferOpeningsOrClosingSelector, bufferClosingSelector) { + return this.window.apply(this, arguments).selectMany(function (x) { return x.toArray(); }); + }; + + /** + * Projects each element of an observable sequence into zero or more windows. + * + * @param {Mixed} windowOpeningsOrClosingSelector Observable sequence whose elements denote the creation of new windows, or, a function invoked to define the boundaries of the produced windows (a new window is started when the previous one is closed, resulting in non-overlapping windows). + * @param {Function} [windowClosingSelector] A function invoked to define the closing of each produced window. If a closing selector function is specified for the first parameter, this parameter is ignored. + * @returns {Observable} An observable sequence of windows. + */ + observableProto.window = function (windowOpeningsOrClosingSelector, windowClosingSelector) { + if (arguments.length === 1 && typeof arguments[0] !== 'function') { + return observableWindowWithBounaries.call(this, windowOpeningsOrClosingSelector); + } + return typeof windowOpeningsOrClosingSelector === 'function' ? + observableWindowWithClosingSelector.call(this, windowOpeningsOrClosingSelector) : + observableWindowWithOpenings.call(this, windowOpeningsOrClosingSelector, windowClosingSelector); + }; + + function observableWindowWithOpenings(windowOpenings, windowClosingSelector) { + return windowOpenings.groupJoin(this, windowClosingSelector, function () { + return observableEmpty(); + }, function (_, window) { + return window; + }); + } + + function observableWindowWithBounaries(windowBoundaries) { + var source = this; + return new AnonymousObservable(function (observer) { + var window = new Subject(), + d = new CompositeDisposable(), + r = new RefCountDisposable(d); + + observer.onNext(addRef(window, r)); + + d.add(source.subscribe(function (x) { + window.onNext(x); + }, function (err) { + window.onError(err); + observer.onError(err); + }, function () { + window.onCompleted(); + observer.onCompleted(); + })); + + d.add(windowBoundaries.subscribe(function (w) { + window.onCompleted(); + window = new Subject(); + observer.onNext(addRef(window, r)); + }, function (err) { + window.onError(err); + observer.onError(err); + }, function () { + window.onCompleted(); + observer.onCompleted(); + })); + + return r; + }); + } + + function observableWindowWithClosingSelector(windowClosingSelector) { + var source = this; + return new AnonymousObservable(function (observer) { + var createWindowClose, + m = new SerialDisposable(), + d = new CompositeDisposable(m), + r = new RefCountDisposable(d), + window = new Subject(); + observer.onNext(addRef(window, r)); + d.add(source.subscribe(function (x) { + window.onNext(x); + }, function (ex) { + window.onError(ex); + observer.onError(ex); + }, function () { + window.onCompleted(); + observer.onCompleted(); + })); + createWindowClose = function () { + var m1, windowClose; + try { + windowClose = windowClosingSelector(); + } catch (exception) { + observer.onError(exception); + return; + } + m1 = new SingleAssignmentDisposable(); + m.setDisposable(m1); + m1.setDisposable(windowClose.take(1).subscribe(noop, function (ex) { + window.onError(ex); + observer.onError(ex); + }, function () { + window.onCompleted(); + window = new Subject(); + observer.onNext(addRef(window, r)); + createWindowClose(); + })); + }; + createWindowClose(); + return r; + }); + } + + /** + * Returns a new observable that triggers on the second and subsequent triggerings of the input observable. + * The Nth triggering of the input observable passes the arguments from the N-1th and Nth triggering as a pair. + * The argument passed to the N-1th triggering is held in hidden internal state until the Nth triggering occurs. + * @returns {Observable} An observable that triggers on successive pairs of observations from the input observable as an array. + */ + observableProto.pairwise = function () { + var source = this; + return new AnonymousObservable(function (observer) { + var previous, hasPrevious = false; + return source.subscribe( + function (x) { + if (hasPrevious) { + observer.onNext([previous, x]); + } else { + hasPrevious = true; + } + previous = x; + }, + observer.onError.bind(observer), + observer.onCompleted.bind(observer)); + }); + }; + /** + * Returns two observables which partition the observations of the source by the given function. + * The first will trigger observations for those values for which the predicate returns true. + * The second will trigger observations for those values where the predicate returns false. + * The predicate is executed once for each subscribed observer. + * Both also propagate all error observations arising from the source and each completes + * when the source completes. + * @param {Function} predicate + * The function to determine which output Observable will trigger a particular observation. + * @returns {Array} + * An array of observables. The first triggers when the predicate returns true, + * and the second triggers when the predicate returns false. + */ + observableProto.partition = function(predicate, thisArg) { + var published = this.publish().refCount(); + return [ + published.filter(predicate, thisArg), + published.filter(function (x, i, o) { return !predicate.call(thisArg, x, i, o); }) + ]; + }; + + function enumerableWhile(condition, source) { + return new Enumerable(function () { + return new Enumerator(function () { + return condition() ? + { done: false, value: source } : + { done: true, value: undefined }; + }); + }); + } + + /** + * Returns an observable sequence that is the result of invoking the selector on the source sequence, without sharing subscriptions. + * This operator allows for a fluent style of writing queries that use the same sequence multiple times. + * + * @param {Function} selector Selector function which can use the source sequence as many times as needed, without sharing subscriptions to the source sequence. + * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. + */ + observableProto.letBind = observableProto['let'] = function (func) { + return func(this); + }; + + /** + * Determines whether an observable collection contains values. There is an alias for this method called 'ifThen' for browsers 0) { + isOwner = !isAcquired; + isAcquired = true; + } + if (isOwner) { + m.setDisposable(scheduler.scheduleRecursive(function (self) { + var work; + if (q.length > 0) { + work = q.shift(); + } else { + isAcquired = false; + return; + } + var m1 = new SingleAssignmentDisposable(); + d.add(m1); + m1.setDisposable(work.subscribe(function (x) { + observer.onNext(x); + var result = null; + try { + result = selector(x); + } catch (e) { + observer.onError(e); + } + q.push(result); + activeCount++; + ensureActive(); + }, observer.onError.bind(observer), function () { + d.remove(m1); + activeCount--; + if (activeCount === 0) { + observer.onCompleted(); + } + })); + self(); + })); + } + }; + + q.push(source); + activeCount++; + ensureActive(); + return d; + }); + }; + + /** + * Runs all observable sequences in parallel and collect their last elements. + * + * @example + * 1 - res = Rx.Observable.forkJoin([obs1, obs2]); + * 1 - res = Rx.Observable.forkJoin(obs1, obs2, ...); + * @returns {Observable} An observable sequence with an array collecting the last elements of all the input sequences. + */ + Observable.forkJoin = function () { + var allSources = argsOrArray(arguments, 0); + return new AnonymousObservable(function (subscriber) { + var count = allSources.length; + if (count === 0) { + subscriber.onCompleted(); + return disposableEmpty; + } + var group = new CompositeDisposable(), + finished = false, + hasResults = new Array(count), + hasCompleted = new Array(count), + results = new Array(count); + + for (var idx = 0; idx < count; idx++) { + (function (i) { + var source = allSources[i]; + isPromise(source) && (source = observableFromPromise(source)); + group.add( + source.subscribe( + function (value) { + if (!finished) { + hasResults[i] = true; + results[i] = value; + } + }, + function (e) { + finished = true; + subscriber.onError(e); + group.dispose(); + }, + function () { + if (!finished) { + if (!hasResults[i]) { + subscriber.onCompleted(); + return; + } + hasCompleted[i] = true; + for (var ix = 0; ix < count; ix++) { + if (!hasCompleted[ix]) { return; } + } + finished = true; + subscriber.onNext(results); + subscriber.onCompleted(); + } + })); + })(idx); + } + + return group; + }); + }; + + /** + * Runs two observable sequences in parallel and combines their last elemenets. + * + * @param {Observable} second Second observable sequence. + * @param {Function} resultSelector Result selector function to invoke with the last elements of both sequences. + * @returns {Observable} An observable sequence with the result of calling the selector function with the last elements of both input sequences. + */ + observableProto.forkJoin = function (second, resultSelector) { + var first = this; + + return new AnonymousObservable(function (observer) { + var leftStopped = false, rightStopped = false, + hasLeft = false, hasRight = false, + lastLeft, lastRight, + leftSubscription = new SingleAssignmentDisposable(), rightSubscription = new SingleAssignmentDisposable(); + + isPromise(second) && (second = observableFromPromise(second)); + + leftSubscription.setDisposable( + first.subscribe(function (left) { + hasLeft = true; + lastLeft = left; + }, function (err) { + rightSubscription.dispose(); + observer.onError(err); + }, function () { + leftStopped = true; + if (rightStopped) { + if (!hasLeft) { + observer.onCompleted(); + } else if (!hasRight) { + observer.onCompleted(); + } else { + var result; + try { + result = resultSelector(lastLeft, lastRight); + } catch (e) { + observer.onError(e); + return; + } + observer.onNext(result); + observer.onCompleted(); + } + } + }) + ); + + rightSubscription.setDisposable( + second.subscribe(function (right) { + hasRight = true; + lastRight = right; + }, function (err) { + leftSubscription.dispose(); + observer.onError(err); + }, function () { + rightStopped = true; + if (leftStopped) { + if (!hasLeft) { + observer.onCompleted(); + } else if (!hasRight) { + observer.onCompleted(); + } else { + var result; + try { + result = resultSelector(lastLeft, lastRight); + } catch (e) { + observer.onError(e); + return; + } + observer.onNext(result); + observer.onCompleted(); + } + } + }) + ); + + return new CompositeDisposable(leftSubscription, rightSubscription); + }); + }; + + /** + * Comonadic bind operator. + * @param {Function} selector A transform function to apply to each element. + * @param {Object} scheduler Scheduler used to execute the operation. If not specified, defaults to the ImmediateScheduler. + * @returns {Observable} An observable sequence which results from the comonadic bind operation. + */ + observableProto.manySelect = function (selector, scheduler) { + scheduler || (scheduler = immediateScheduler); + var source = this; + return observableDefer(function () { + var chain; + + return source + .select( + function (x) { + var curr = new ChainObservable(x); + if (chain) { + chain.onNext(x); + } + chain = curr; + + return curr; + }) + .doAction( + noop, + function (e) { + if (chain) { + chain.onError(e); + } + }, + function () { + if (chain) { + chain.onCompleted(); + } + }) + .observeOn(scheduler) + .select(function (x, i, o) { return selector(x, i, o); }); + }); + }; + + var ChainObservable = (function (_super) { + + function subscribe (observer) { + var self = this, g = new CompositeDisposable(); + g.add(currentThreadScheduler.schedule(function () { + observer.onNext(self.head); + g.add(self.tail.mergeObservable().subscribe(observer)); + })); + + return g; + } + + inherits(ChainObservable, _super); + + function ChainObservable(head) { + _super.call(this, subscribe); + this.head = head; + this.tail = new AsyncSubject(); + } + + addProperties(ChainObservable.prototype, Observer, { + onCompleted: function () { + this.onNext(Observable.empty()); + }, + onError: function (e) { + this.onNext(Observable.throwException(e)); + }, + onNext: function (v) { + this.tail.onNext(v); + this.tail.onCompleted(); + } + }); + + return ChainObservable; + + }(Observable)); + + /** @private */ + var Map = (function () { + + /** + * @constructor + * @private + */ + function Map() { + this.keys = []; + this.values = []; + } + + /** + * @private + * @memberOf Map# + */ + Map.prototype['delete'] = function (key) { + var i = this.keys.indexOf(key); + if (i !== -1) { + this.keys.splice(i, 1); + this.values.splice(i, 1); + } + return i !== -1; + }; + + /** + * @private + * @memberOf Map# + */ + Map.prototype.get = function (key, fallback) { + var i = this.keys.indexOf(key); + return i !== -1 ? this.values[i] : fallback; + }; + + /** + * @private + * @memberOf Map# + */ + Map.prototype.set = function (key, value) { + var i = this.keys.indexOf(key); + if (i !== -1) { + this.values[i] = value; + } + this.values[this.keys.push(key) - 1] = value; + }; + + /** + * @private + * @memberOf Map# + */ + Map.prototype.size = function () { return this.keys.length; }; + + /** + * @private + * @memberOf Map# + */ + Map.prototype.has = function (key) { + return this.keys.indexOf(key) !== -1; + }; + + /** + * @private + * @memberOf Map# + */ + Map.prototype.getKeys = function () { return this.keys.slice(0); }; + + /** + * @private + * @memberOf Map# + */ + Map.prototype.getValues = function () { return this.values.slice(0); }; + + return Map; + }()); + + /** + * @constructor + * Represents a join pattern over observable sequences. + */ + function Pattern(patterns) { + this.patterns = patterns; + } + + /** + * Creates a pattern that matches the current plan matches and when the specified observable sequences has an available value. + * + * @param other Observable sequence to match in addition to the current pattern. + * @return Pattern object that matches when all observable sequences in the pattern have an available value. + */ + Pattern.prototype.and = function (other) { + var patterns = this.patterns.slice(0); + patterns.push(other); + return new Pattern(patterns); + }; + + /** + * Matches when all observable sequences in the pattern (specified using a chain of and operators) have an available value and projects the values. + * + * @param selector Selector that will be invoked with available values from the source sequences, in the same order of the sequences in the pattern. + * @return Plan that produces the projected values, to be fed (with other plans) to the when operator. + */ + Pattern.prototype.then = function (selector) { + return new Plan(this, selector); + }; + + function Plan(expression, selector) { + this.expression = expression; + this.selector = selector; + } + + Plan.prototype.activate = function (externalSubscriptions, observer, deactivate) { + var self = this; + var joinObservers = []; + for (var i = 0, len = this.expression.patterns.length; i < len; i++) { + joinObservers.push(planCreateObserver(externalSubscriptions, this.expression.patterns[i], observer.onError.bind(observer))); + } + var activePlan = new ActivePlan(joinObservers, function () { + var result; + try { + result = self.selector.apply(self, arguments); + } catch (exception) { + observer.onError(exception); + return; + } + observer.onNext(result); + }, function () { + for (var j = 0, jlen = joinObservers.length; j < jlen; j++) { + joinObservers[j].removeActivePlan(activePlan); + } + deactivate(activePlan); + }); + for (i = 0, len = joinObservers.length; i < len; i++) { + joinObservers[i].addActivePlan(activePlan); + } + return activePlan; + }; + + function planCreateObserver(externalSubscriptions, observable, onError) { + var entry = externalSubscriptions.get(observable); + if (!entry) { + var observer = new JoinObserver(observable, onError); + externalSubscriptions.set(observable, observer); + return observer; + } + return entry; + } + + // Active Plan + function ActivePlan(joinObserverArray, onNext, onCompleted) { + var i, joinObserver; + this.joinObserverArray = joinObserverArray; + this.onNext = onNext; + this.onCompleted = onCompleted; + this.joinObservers = new Map(); + for (i = 0; i < this.joinObserverArray.length; i++) { + joinObserver = this.joinObserverArray[i]; + this.joinObservers.set(joinObserver, joinObserver); + } + } + + ActivePlan.prototype.dequeue = function () { + var values = this.joinObservers.getValues(); + for (var i = 0, len = values.length; i < len; i++) { + values[i].queue.shift(); + } + }; + ActivePlan.prototype.match = function () { + var firstValues, i, len, isCompleted, values, hasValues = true; + for (i = 0, len = this.joinObserverArray.length; i < len; i++) { + if (this.joinObserverArray[i].queue.length === 0) { + hasValues = false; + break; + } + } + if (hasValues) { + firstValues = []; + isCompleted = false; + for (i = 0, len = this.joinObserverArray.length; i < len; i++) { + firstValues.push(this.joinObserverArray[i].queue[0]); + if (this.joinObserverArray[i].queue[0].kind === 'C') { + isCompleted = true; + } + } + if (isCompleted) { + this.onCompleted(); + } else { + this.dequeue(); + values = []; + for (i = 0; i < firstValues.length; i++) { + values.push(firstValues[i].value); + } + this.onNext.apply(this, values); + } + } + }; + + /** @private */ + var JoinObserver = (function (_super) { + + inherits(JoinObserver, _super); + + /** + * @constructor + * @private + */ + function JoinObserver(source, onError) { + _super.call(this); + this.source = source; + this.onError = onError; + this.queue = []; + this.activePlans = []; + this.subscription = new SingleAssignmentDisposable(); + this.isDisposed = false; + } + + var JoinObserverPrototype = JoinObserver.prototype; + + /** + * @memberOf JoinObserver# + * @private + */ + JoinObserverPrototype.next = function (notification) { + if (!this.isDisposed) { + if (notification.kind === 'E') { + this.onError(notification.exception); + return; + } + this.queue.push(notification); + var activePlans = this.activePlans.slice(0); + for (var i = 0, len = activePlans.length; i < len; i++) { + activePlans[i].match(); + } + } + }; + + /** + * @memberOf JoinObserver# + * @private + */ + JoinObserverPrototype.error = noop; + + /** + * @memberOf JoinObserver# + * @private + */ + JoinObserverPrototype.completed = noop; + + /** + * @memberOf JoinObserver# + * @private + */ + JoinObserverPrototype.addActivePlan = function (activePlan) { + this.activePlans.push(activePlan); + }; + + /** + * @memberOf JoinObserver# + * @private + */ + JoinObserverPrototype.subscribe = function () { + this.subscription.setDisposable(this.source.materialize().subscribe(this)); + }; + + /** + * @memberOf JoinObserver# + * @private + */ + JoinObserverPrototype.removeActivePlan = function (activePlan) { + var idx = this.activePlans.indexOf(activePlan); + this.activePlans.splice(idx, 1); + if (this.activePlans.length === 0) { + this.dispose(); + } + }; + + /** + * @memberOf JoinObserver# + * @private + */ + JoinObserverPrototype.dispose = function () { + _super.prototype.dispose.call(this); + if (!this.isDisposed) { + this.isDisposed = true; + this.subscription.dispose(); + } + }; + + return JoinObserver; + } (AbstractObserver)); + + /** + * Creates a pattern that matches when both observable sequences have an available value. + * + * @param right Observable sequence to match with the current sequence. + * @return {Pattern} Pattern object that matches when both observable sequences have an available value. + */ + observableProto.and = function (right) { + return new Pattern([this, right]); + }; + + /** + * Matches when the observable sequence has an available value and projects the value. + * + * @param selector Selector that will be invoked for values in the source sequence. + * @returns {Plan} Plan that produces the projected values, to be fed (with other plans) to the when operator. + */ + observableProto.then = function (selector) { + return new Pattern([this]).then(selector); + }; + + /** + * Joins together the results from several patterns. + * + * @param plans A series of plans (specified as an Array of as a series of arguments) created by use of the Then operator on patterns. + * @returns {Observable} Observable sequence with the results form matching several patterns. + */ + Observable.when = function () { + var plans = argsOrArray(arguments, 0); + return new AnonymousObservable(function (observer) { + var activePlans = [], + externalSubscriptions = new Map(), + group, + i, len, + joinObserver, + joinValues, + outObserver; + outObserver = observerCreate(observer.onNext.bind(observer), function (exception) { + var values = externalSubscriptions.getValues(); + for (var j = 0, jlen = values.length; j < jlen; j++) { + values[j].onError(exception); + } + observer.onError(exception); + }, observer.onCompleted.bind(observer)); + try { + for (i = 0, len = plans.length; i < len; i++) { + activePlans.push(plans[i].activate(externalSubscriptions, outObserver, function (activePlan) { + var idx = activePlans.indexOf(activePlan); + activePlans.splice(idx, 1); + if (activePlans.length === 0) { + outObserver.onCompleted(); + } + })); + } + } catch (e) { + observableThrow(e).subscribe(observer); + } + group = new CompositeDisposable(); + joinValues = externalSubscriptions.getValues(); + for (i = 0, len = joinValues.length; i < len; i++) { + joinObserver = joinValues[i]; + joinObserver.subscribe(); + group.add(joinObserver); + } + return group; + }); + }; + + function observableTimerDate(dueTime, scheduler) { + return new AnonymousObservable(function (observer) { + return scheduler.scheduleWithAbsolute(dueTime, function () { + observer.onNext(0); + observer.onCompleted(); + }); + }); + } + + function observableTimerDateAndPeriod(dueTime, period, scheduler) { + var p = normalizeTime(period); + return new AnonymousObservable(function (observer) { + var count = 0, d = dueTime; + return scheduler.scheduleRecursiveWithAbsolute(d, function (self) { + var now; + if (p > 0) { + now = scheduler.now(); + d = d + p; + if (d <= now) { + d = now + p; + } + } + observer.onNext(count++); + self(d); + }); + }); + } + + function observableTimerTimeSpan(dueTime, scheduler) { + var d = normalizeTime(dueTime); + return new AnonymousObservable(function (observer) { + return scheduler.scheduleWithRelative(d, function () { + observer.onNext(0); + observer.onCompleted(); + }); + }); + } + + function observableTimerTimeSpanAndPeriod(dueTime, period, scheduler) { + if (dueTime === period) { + return new AnonymousObservable(function (observer) { + return scheduler.schedulePeriodicWithState(0, period, function (count) { + observer.onNext(count); + return count + 1; + }); + }); + } + return 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) { + scheduler || (scheduler = timeoutScheduler); + return observableTimerTimeSpanAndPeriod(period, period, scheduler); + }; + + /** + * Returns an observable sequence that produces a value after dueTime has elapsed and then after each period. + * + * @example + * 1 - res = Rx.Observable.timer(new Date()); + * 2 - res = Rx.Observable.timer(new Date(), 1000); + * 3 - res = Rx.Observable.timer(new Date(), Rx.Scheduler.timeout); + * 4 - res = Rx.Observable.timer(new Date(), 1000, Rx.Scheduler.timeout); + * + * 5 - res = Rx.Observable.timer(5000); + * 6 - res = Rx.Observable.timer(5000, 1000); + * 7 - res = Rx.Observable.timer(5000, Rx.Scheduler.timeout); + * 8 - res = Rx.Observable.timer(5000, 1000, Rx.Scheduler.timeout); + * + * @param {Number} dueTime Absolute (specified as a Date object) or relative time (specified as an integer denoting milliseconds) at which to produce the first value. + * @param {Mixed} [periodOrScheduler] Period to produce subsequent values (specified as an integer denoting milliseconds), or the scheduler to run the timer on. If not specified, the resulting timer is not recurring. + * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, the timeout scheduler is used. + * @returns {Observable} An observable sequence that produces a value after due time has elapsed and then each period. + */ + var observableTimer = Observable.timer = function (dueTime, periodOrScheduler, scheduler) { + var period; + scheduler || (scheduler = timeoutScheduler); + if (periodOrScheduler !== undefined && typeof periodOrScheduler === 'number') { + period = periodOrScheduler; + } else if (periodOrScheduler !== undefined && typeof periodOrScheduler === 'object') { + scheduler = periodOrScheduler; + } + if (dueTime instanceof Date && period === undefined) { + return observableTimerDate(dueTime.getTime(), scheduler); + } + if (dueTime instanceof Date && period !== undefined) { + period = periodOrScheduler; + return observableTimerDateAndPeriod(dueTime.getTime(), period, scheduler); + } + if (period === undefined) { + return observableTimerTimeSpan(dueTime, scheduler); + } + return observableTimerTimeSpanAndPeriod(dueTime, period, scheduler); + }; + + function observableDelayTimeSpan(dueTime, scheduler) { + var source = this; + return new AnonymousObservable(function (observer) { + var active = false, + cancelable = new SerialDisposable(), + exception = null, + q = [], + running = false, + subscription; + subscription = source.materialize().timestamp(scheduler).subscribe(function (notification) { + var d, shouldRun; + if (notification.value.kind === 'E') { + q = []; + q.push(notification); + exception = notification.value.exception; + shouldRun = !running; + } else { + q.push({ value: notification.value, timestamp: notification.timestamp + dueTime }); + shouldRun = !active; + active = true; + } + if (shouldRun) { + if (exception !== null) { + observer.onError(exception); + } else { + d = new SingleAssignmentDisposable(); + cancelable.setDisposable(d); + d.setDisposable(scheduler.scheduleRecursiveWithRelative(dueTime, function (self) { + var e, recurseDueTime, result, shouldRecurse; + if (exception !== null) { + return; + } + running = true; + do { + result = null; + if (q.length > 0 && q[0].timestamp - scheduler.now() <= 0) { + result = q.shift().value; + } + if (result !== null) { + result.accept(observer); + } + } while (result !== null); + shouldRecurse = false; + recurseDueTime = 0; + if (q.length > 0) { + shouldRecurse = true; + recurseDueTime = Math.max(0, q[0].timestamp - scheduler.now()); + } else { + active = false; + } + e = exception; + running = false; + if (e !== null) { + observer.onError(e); + } else if (shouldRecurse) { + self(recurseDueTime); + } + })); + } + } + }); + return new CompositeDisposable(subscription, cancelable); + }); + } + + function observableDelayDate(dueTime, scheduler) { + var self = this; + return observableDefer(function () { + var timeSpan = dueTime - scheduler.now(); + return observableDelayTimeSpan.call(self, timeSpan, 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) { + scheduler || (scheduler = timeoutScheduler); + return dueTime instanceof Date ? + observableDelayDate.call(this, dueTime.getTime(), scheduler) : + observableDelayTimeSpan.call(this, dueTime, scheduler); + }; + + /** + * Ignores values from an observable sequence which are followed by another value before dueTime. + * + * @example + * 1 - res = source.throttle(5000); // 5 seconds + * 2 - res = source.throttle(5000, scheduler); + * + * @param {Number} dueTime Duration of the throttle period for each value (specified as an integer denoting milliseconds). + * @param {Scheduler} [scheduler] Scheduler to run the throttle timers on. If not specified, the timeout scheduler is used. + * @returns {Observable} The throttled sequence. + */ + observableProto.throttle = function (dueTime, scheduler) { + scheduler || (scheduler = timeoutScheduler); + var source = this; + return this.throttleWithSelector(function () { return observableTimer(dueTime, scheduler); }) + }; + + /** + * Projects each element of an observable sequence into zero or more windows which are produced based on timing information. + * + * @example + * 1 - res = xs.windowWithTime(1000, scheduler); // non-overlapping segments of 1 second + * 2 - res = xs.windowWithTime(1000, 500 , scheduler); // segments of 1 second with time shift 0.5 seconds + * + * @param {Number} timeSpan Length of each window (specified as an integer denoting milliseconds). + * @param {Mixed} [timeShiftOrScheduler] Interval between creation of consecutive windows (specified as an integer denoting milliseconds), or an optional scheduler parameter. If not specified, the time shift corresponds to the timeSpan parameter, resulting in non-overlapping adjacent windows. + * @param {Scheduler} [scheduler] Scheduler to run windowing timers on. If not specified, the timeout scheduler is used. + * @returns {Observable} An observable sequence of windows. + */ + observableProto.windowWithTime = function (timeSpan, timeShiftOrScheduler, scheduler) { + var source = this, timeShift; + if (timeShiftOrScheduler === undefined) { + timeShift = timeSpan; + } + if (scheduler === undefined) { + scheduler = timeoutScheduler; + } + if (typeof timeShiftOrScheduler === 'number') { + timeShift = timeShiftOrScheduler; + } else if (typeof timeShiftOrScheduler === 'object') { + timeShift = timeSpan; + scheduler = timeShiftOrScheduler; + } + return new AnonymousObservable(function (observer) { + var groupDisposable, + nextShift = timeShift, + nextSpan = timeSpan, + q = [], + refCountDisposable, + timerD = new SerialDisposable(), + totalTime = 0; + groupDisposable = new CompositeDisposable(timerD), + refCountDisposable = new RefCountDisposable(groupDisposable); + + 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 () { + var s; + if (isShift) { + s = new Subject(); + q.push(s); + observer.onNext(addRef(s, refCountDisposable)); + } + if (isSpan) { + s = q.shift(); + s.onCompleted(); + } + createTimer(); + })); + }; + q.push(new Subject()); + observer.onNext(addRef(q[0], refCountDisposable)); + createTimer(); + groupDisposable.add(source.subscribe(function (x) { + var i, s; + for (i = 0; i < q.length; i++) { + s = q[i]; + s.onNext(x); + } + }, function (e) { + var i, s; + for (i = 0; i < q.length; i++) { + s = q[i]; + s.onError(e); + } + observer.onError(e); + }, function () { + var i, s; + for (i = 0; i < q.length; i++) { + s = q[i]; + s.onCompleted(); + } + observer.onCompleted(); + })); + return refCountDisposable; + }); + }; + + /** + * Projects each element of an observable sequence into a window that is completed when either it's full or a given amount of time has elapsed. + * @example + * 1 - res = source.windowWithTimeOrCount(5000, 50); // 5s or 50 items + * 2 - res = source.windowWithTimeOrCount(5000, 50, scheduler); //5s or 50 items + * + * @memberOf Observable# + * @param {Number} timeSpan Maximum time length of a window. + * @param {Number} count Maximum element count of a window. + * @param {Scheduler} [scheduler] Scheduler to run windowing timers on. If not specified, the timeout scheduler is used. + * @returns {Observable} An observable sequence of windows. + */ + observableProto.windowWithTimeOrCount = function (timeSpan, count, scheduler) { + var source = this; + scheduler || (scheduler = timeoutScheduler); + return new AnonymousObservable(function (observer) { + var createTimer, + groupDisposable, + n = 0, + refCountDisposable, + s, + timerD = new SerialDisposable(), + windowId = 0; + groupDisposable = new CompositeDisposable(timerD); + refCountDisposable = new RefCountDisposable(groupDisposable); + createTimer = function (id) { + var m = new SingleAssignmentDisposable(); + timerD.setDisposable(m); + m.setDisposable(scheduler.scheduleWithRelative(timeSpan, function () { + var newId; + if (id !== windowId) { + return; + } + n = 0; + newId = ++windowId; + s.onCompleted(); + s = new Subject(); + observer.onNext(addRef(s, refCountDisposable)); + createTimer(newId); + })); + }; + s = new Subject(); + observer.onNext(addRef(s, refCountDisposable)); + createTimer(0); + groupDisposable.add(source.subscribe(function (x) { + var newId = 0, newWindow = false; + s.onNext(x); + n++; + if (n === count) { + newWindow = true; + n = 0; + newId = ++windowId; + s.onCompleted(); + s = new Subject(); + observer.onNext(addRef(s, refCountDisposable)); + } + if (newWindow) { + createTimer(newId); + } + }, function (e) { + s.onError(e); + observer.onError(e); + }, function () { + s.onCompleted(); + observer.onCompleted(); + })); + return refCountDisposable; + }); + }; + + /** + * 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; + scheduler || (scheduler = timeoutScheduler); + return observableDefer(function () { + var last = scheduler.now(); + return source.select(function (x) { + var now = scheduler.now(), span = now - last; + last = now; + return { + value: x, + interval: span + }; + }); + }); + }; + + /** + * Records the timestamp for each value in an observable sequence. + * + * @example + * 1 - res = source.timestamp(); // produces { value: x, timestamp: ts } + * 2 - res = source.timestamp(Rx.Scheduler.timeout); + * + * @param {Scheduler} [scheduler] Scheduler used to compute timestamps. If not specified, the timeout scheduler is used. + * @returns {Observable} An observable sequence with timestamp information on values. + */ + observableProto.timestamp = function (scheduler) { + scheduler || (scheduler = timeoutScheduler); + return this.select(function (x) { + return { + value: x, + timestamp: scheduler.now() + }; + }); + }; + + function sampleObservable(source, sampler) { + + return new AnonymousObservable(function (observer) { + var atEnd, value, hasValue; + + function sampleSubscribe() { + if (hasValue) { + hasValue = false; + observer.onNext(value); + } + if (atEnd) { + observer.onCompleted(); + } + } + + return new CompositeDisposable( + source.subscribe(function (newValue) { + hasValue = true; + value = newValue; + }, observer.onError.bind(observer), function () { + atEnd = true; + }), + sampler.subscribe(sampleSubscribe, observer.onError.bind(observer), sampleSubscribe) + ); + }); + } + + /** + * Samples the observable sequence at each interval. + * + * @example + * 1 - res = source.sample(sampleObservable); // Sampler tick sequence + * 2 - res = source.sample(5000); // 5 seconds + * 2 - res = source.sample(5000, Rx.Scheduler.timeout); // 5 seconds + * + * @param {Mixed} intervalOrSampler Interval at which to sample (specified as an integer denoting milliseconds) or Sampler Observable. + * @param {Scheduler} [scheduler] Scheduler to run the sampling timer on. If not specified, the timeout scheduler is used. + * @returns {Observable} Sampled observable sequence. + */ + observableProto.sample = function (intervalOrSampler, scheduler) { + scheduler || (scheduler = timeoutScheduler); + if (typeof intervalOrSampler === 'number') { + return sampleObservable(this, observableinterval(intervalOrSampler, scheduler)); + } + return sampleObservable(this, intervalOrSampler); + }; + + /** + * Returns the source observable sequence or the other observable sequence if dueTime elapses. + * + * @example + * 1 - res = source.timeout(new Date()); // As a date + * 2 - res = source.timeout(5000); // 5 seconds + * 3 - res = source.timeout(new Date(), Rx.Observable.returnValue(42)); // As a date and timeout observable + * 4 - res = source.timeout(5000, Rx.Observable.returnValue(42)); // 5 seconds and timeout observable + * 5 - res = source.timeout(new Date(), Rx.Observable.returnValue(42), Rx.Scheduler.timeout); // As a date and timeout observable + * 6 - res = source.timeout(5000, Rx.Observable.returnValue(42), Rx.Scheduler.timeout); // 5 seconds and timeout observable + * + * @param {Number} dueTime Absolute (specified as a Date object) or relative time (specified as an integer denoting milliseconds) when a timeout occurs. + * @param {Observable} [other] Sequence to return in case of a timeout. If not specified, a timeout error throwing sequence will be used. + * @param {Scheduler} [scheduler] Scheduler to run the timeout timers on. If not specified, the timeout scheduler is used. + * @returns {Observable} The source sequence switching to the other sequence in case of a timeout. + */ + observableProto.timeout = function (dueTime, other, scheduler) { + other || (other = observableThrow(new Error('Timeout'))); + scheduler || (scheduler = timeoutScheduler); + + var source = this, schedulerMethod = dueTime instanceof Date ? + 'scheduleWithAbsolute' : + 'scheduleWithRelative'; + + return new AnonymousObservable(function (observer) { + var id = 0, + original = new SingleAssignmentDisposable(), + subscription = new SerialDisposable(), + switched = false, + timer = new SerialDisposable(); + + subscription.setDisposable(original); + + var createTimer = function () { + var myId = id; + timer.setDisposable(scheduler[schedulerMethod](dueTime, function () { + if (id === myId) { + isPromise(other) && (other = observableFromPromise(other)); + subscription.setDisposable(other.subscribe(observer)); + } + })); + }; + + createTimer(); + + original.setDisposable(source.subscribe(function (x) { + if (!switched) { + id++; + observer.onNext(x); + createTimer(); + } + }, function (e) { + if (!switched) { + id++; + observer.onError(e); + } + }, function () { + if (!switched) { + id++; + observer.onCompleted(); + } + })); + return new CompositeDisposable(subscription, timer); + }); + }; + + /** + * Generates an observable sequence by iterating a state from an initial state until the condition fails. + * + * @example + * res = source.generateWithAbsoluteTime(0, + * function (x) { return return true; }, + * function (x) { return x + 1; }, + * function (x) { return x; }, + * function (x) { return new Date(); } + * }); + * + * @param {Mixed} initialState Initial state. + * @param {Function} condition Condition to terminate generation (upon returning false). + * @param {Function} iterate Iteration step function. + * @param {Function} resultSelector Selector function for results produced in the sequence. + * @param {Function} timeSelector Time selector function to control the speed of values being produced each iteration, returning Date values. + * @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not specified, the timeout scheduler is used. + * @returns {Observable} The generated sequence. + */ + Observable.generateWithAbsoluteTime = function (initialState, condition, iterate, resultSelector, timeSelector, scheduler) { + scheduler || (scheduler = timeoutScheduler); + return new AnonymousObservable(function (observer) { + var first = true, + hasResult = false, + result, + state = initialState, + time; + return scheduler.scheduleRecursiveWithAbsolute(scheduler.now(), function (self) { + if (hasResult) { + observer.onNext(result); + } + try { + if (first) { + first = false; + } else { + state = iterate(state); + } + hasResult = condition(state); + if (hasResult) { + result = resultSelector(state); + time = timeSelector(state); + } + } catch (e) { + observer.onError(e); + return; + } + if (hasResult) { + self(time); + } else { + observer.onCompleted(); + } + }); + }); + }; + + /** + * Generates an observable sequence by iterating a state from an initial state until the condition fails. + * + * @example + * res = source.generateWithRelativeTime(0, + * function (x) { return return true; }, + * function (x) { return x + 1; }, + * function (x) { return x; }, + * function (x) { return 500; } + * ); + * + * @param {Mixed} initialState Initial state. + * @param {Function} condition Condition to terminate generation (upon returning false). + * @param {Function} iterate Iteration step function. + * @param {Function} resultSelector Selector function for results produced in the sequence. + * @param {Function} timeSelector Time selector function to control the speed of values being produced each iteration, returning integer values denoting milliseconds. + * @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not specified, the timeout scheduler is used. + * @returns {Observable} The generated sequence. + */ + Observable.generateWithRelativeTime = function (initialState, condition, iterate, resultSelector, timeSelector, scheduler) { + scheduler || (scheduler = timeoutScheduler); + return new AnonymousObservable(function (observer) { + var first = true, + hasResult = false, + result, + state = initialState, + time; + return scheduler.scheduleRecursiveWithRelative(0, function (self) { + if (hasResult) { + observer.onNext(result); + } + try { + if (first) { + first = false; + } else { + state = iterate(state); + } + hasResult = condition(state); + if (hasResult) { + result = resultSelector(state); + time = timeSelector(state); + } + } catch (e) { + observer.onError(e); + return; + } + if (hasResult) { + self(time); + } else { + observer.onCompleted(); + } + }); + }); + }; + + /** + * Time shifts the observable sequence by delaying the subscription. + * + * @example + * 1 - res = source.delaySubscription(5000); // 5s + * 2 - res = source.delaySubscription(5000, Rx.Scheduler.timeout); // 5 seconds + * + * @param {Number} dueTime Absolute or relative time to perform the subscription at. + * @param {Scheduler} [scheduler] Scheduler to run the subscription delay timer on. If not specified, the timeout scheduler is used. + * @returns {Observable} Time-shifted sequence. + */ + observableProto.delaySubscription = function (dueTime, scheduler) { + scheduler || (scheduler = timeoutScheduler); + return this.delayWithSelector(observableTimer(dueTime, scheduler), function () { return observableEmpty(); }); + }; + + /** + * Time shifts the observable sequence based on a subscription delay and a delay selector function for each element. + * + * @example + * 1 - res = source.delayWithSelector(function (x) { return Rx.Scheduler.timer(5000); }); // with selector only + * 1 - res = source.delayWithSelector(Rx.Observable.timer(2000), function (x) { return Rx.Observable.timer(x); }); // with delay and selector + * + * @param {Observable} [subscriptionDelay] Sequence indicating the delay for the subscription to the source. + * @param {Function} delayDurationSelector Selector function to retrieve a sequence indicating the delay for each given element. + * @returns {Observable} Time-shifted sequence. + */ + observableProto.delayWithSelector = function (subscriptionDelay, delayDurationSelector) { + var source = this, subDelay, selector; + if (typeof subscriptionDelay === 'function') { + selector = subscriptionDelay; + } else { + subDelay = subscriptionDelay; + selector = delayDurationSelector; + } + return new AnonymousObservable(function (observer) { + var delays = new CompositeDisposable(), atEnd = false, done = function () { + if (atEnd && delays.length === 0) { + observer.onCompleted(); + } + }, subscription = new SerialDisposable(), start = function () { + subscription.setDisposable(source.subscribe(function (x) { + var delay; + try { + delay = selector(x); + } catch (error) { + observer.onError(error); + return; + } + var d = new SingleAssignmentDisposable(); + delays.add(d); + d.setDisposable(delay.subscribe(function () { + observer.onNext(x); + delays.remove(d); + done(); + }, observer.onError.bind(observer), function () { + observer.onNext(x); + delays.remove(d); + done(); + })); + }, observer.onError.bind(observer), function () { + atEnd = true; + subscription.dispose(); + done(); + })); + }; + + if (!subDelay) { + start(); + } else { + subscription.setDisposable(subDelay.subscribe(function () { + start(); + }, observer.onError.bind(observer), function () { start(); })); + } + + return new CompositeDisposable(subscription, delays); + }); + }; + + /** + * Returns the source observable sequence, switching to the other observable sequence if a timeout is signaled. + * + * @example + * 1 - res = source.timeoutWithSelector(Rx.Observable.timer(500)); + * 2 - res = source.timeoutWithSelector(Rx.Observable.timer(500), function (x) { return Rx.Observable.timer(200); }); + * 3 - res = source.timeoutWithSelector(Rx.Observable.timer(500), function (x) { return Rx.Observable.timer(200); }, Rx.Observable.returnValue(42)); + * + * @param {Observable} [firstTimeout] Observable sequence that represents the timeout for the first element. If not provided, this defaults to Observable.never(). + * @param {Function} [timeoutDurationSelector] Selector to retrieve an observable sequence that represents the timeout between the current element and the next element. + * @param {Observable} [other] Sequence to return in case of a timeout. If not provided, this is set to Observable.throwException(). + * @returns {Observable} The source sequence switching to the other sequence in case of a timeout. + */ + observableProto.timeoutWithSelector = function (firstTimeout, timeoutdurationSelector, other) { + if (arguments.length === 1) { + timeoutdurationSelector = firstTimeout; + var firstTimeout = observableNever(); + } + other || (other = observableThrow(new Error('Timeout'))); + var source = this; + return new AnonymousObservable(function (observer) { + var subscription = new SerialDisposable(), timer = new SerialDisposable(), original = new SingleAssignmentDisposable(); + + subscription.setDisposable(original); + + var id = 0, switched = false, setTimer = function (timeout) { + var myId = id, timerWins = function () { + return id === myId; + }; + var d = new SingleAssignmentDisposable(); + timer.setDisposable(d); + d.setDisposable(timeout.subscribe(function () { + if (timerWins()) { + subscription.setDisposable(other.subscribe(observer)); + } + d.dispose(); + }, function (e) { + if (timerWins()) { + observer.onError(e); + } + }, function () { + if (timerWins()) { + subscription.setDisposable(other.subscribe(observer)); + } + })); + }; + + setTimer(firstTimeout); + var observerWins = function () { + var res = !switched; + if (res) { + id++; + } + return res; + }; + + original.setDisposable(source.subscribe(function (x) { + if (observerWins()) { + observer.onNext(x); + var timeout; + try { + timeout = timeoutdurationSelector(x); + } catch (e) { + observer.onError(e); + return; + } + setTimer(timeout); + } + }, function (e) { + if (observerWins()) { + observer.onError(e); + } + }, function () { + if (observerWins()) { + observer.onCompleted(); + } + })); + return new CompositeDisposable(subscription, timer); + }); + }; + + /** + * Ignores values from an observable sequence which are followed by another value within a computed throttle duration. + * + * @example + * 1 - res = source.delayWithSelector(function (x) { return Rx.Scheduler.timer(x + x); }); + * + * @param {Function} throttleDurationSelector Selector function to retrieve a sequence indicating the throttle duration for each given element. + * @returns {Observable} The throttled sequence. + */ + observableProto.throttleWithSelector = function (throttleDurationSelector) { + var source = this; + return new AnonymousObservable(function (observer) { + var value, hasValue = false, cancelable = new SerialDisposable(), id = 0, subscription = source.subscribe(function (x) { + var throttle; + try { + throttle = throttleDurationSelector(x); + } catch (e) { + observer.onError(e); + return; + } + hasValue = true; + value = x; + id++; + var currentid = id, d = new SingleAssignmentDisposable(); + cancelable.setDisposable(d); + d.setDisposable(throttle.subscribe(function () { + if (hasValue && id === currentid) { + observer.onNext(value); + } + hasValue = false; + d.dispose(); + }, observer.onError.bind(observer), function () { + if (hasValue && id === currentid) { + observer.onNext(value); + } + hasValue = false; + d.dispose(); + })); + }, function (e) { + cancelable.dispose(); + observer.onError(e); + hasValue = false; + id++; + }, function () { + cancelable.dispose(); + if (hasValue) { + observer.onNext(value); + } + observer.onCompleted(); + hasValue = false; + id++; + }); + return new CompositeDisposable(subscription, cancelable); + }); + }; + + /** + * Skips elements for the specified duration from the end of the observable source sequence, using the specified scheduler to run timers. + * + * 1 - res = source.skipLastWithTime(5000); + * 2 - res = source.skipLastWithTime(5000, scheduler); + * + * @description + * This operator accumulates a queue with a length enough to store elements received during the initial duration window. + * As more elements are received, elements older than the specified duration are taken from the queue and produced on the + * result sequence. This causes elements to be delayed with duration. + * @param {Number} duration Duration for skipping elements from the end of the sequence. + * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout + * @returns {Observable} An observable sequence with the elements skipped during the specified duration from the end of the source sequence. + */ + observableProto.skipLastWithTime = function (duration, scheduler) { + scheduler || (scheduler = timeoutScheduler); + var source = this; + return new AnonymousObservable(function (observer) { + var q = []; + return source.subscribe(function (x) { + var now = scheduler.now(); + q.push({ interval: now, value: x }); + while (q.length > 0 && now - q[0].interval >= duration) { + observer.onNext(q.shift().value); + } + }, observer.onError.bind(observer), function () { + var now = scheduler.now(); + while (q.length > 0 && now - q[0].interval >= duration) { + observer.onNext(q.shift().value); + } + observer.onCompleted(); + }); + }); + }; + + /** + * Returns elements within the specified duration from the end of the observable source sequence, using the specified schedulers to run timers and to drain the collected elements. + * + * @example + * 1 - res = source.takeLastWithTime(5000, [optional timer scheduler], [optional loop scheduler]); + * @description + * This operator accumulates a queue with a length enough to store elements received during the initial duration window. + * As more elements are received, elements older than the specified duration are taken from the queue and produced on the + * result sequence. This causes elements to be delayed with duration. + * @param {Number} duration Duration for taking elements from the end of the sequence. + * @param {Scheduler} [timerScheduler] Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. + * @param {Scheduler} [loopScheduler] Scheduler to drain the collected elements. If not specified, defaults to Rx.Scheduler.immediate. + * @returns {Observable} An observable sequence with the elements taken during the specified duration from the end of the source sequence. + */ + observableProto.takeLastWithTime = function (duration, timerScheduler, loopScheduler) { + return this.takeLastBufferWithTime(duration, timerScheduler).selectMany(function (xs) { return observableFromArray(xs, loopScheduler); }); + }; + + /** + * Returns an array with the elements within the specified duration from the end of the observable source sequence, using the specified scheduler to run timers. + * + * @example + * 1 - res = source.takeLastBufferWithTime(5000, [optional scheduler]); + * @description + * This operator accumulates a queue with a length enough to store elements received during the initial duration window. + * As more elements are received, elements older than the specified duration are taken from the queue and produced on the + * result sequence. This causes elements to be delayed with duration. + * @param {Number} duration Duration for taking elements from the end of the sequence. + * @param {Scheduler} scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. + * @returns {Observable} An observable sequence containing a single array with the elements taken during the specified duration from the end of the source sequence. + */ + observableProto.takeLastBufferWithTime = function (duration, scheduler) { + var source = this; + scheduler || (scheduler = timeoutScheduler); + return new AnonymousObservable(function (observer) { + var q = []; + + return source.subscribe(function (x) { + var now = scheduler.now(); + q.push({ interval: now, value: x }); + while (q.length > 0 && now - q[0].interval >= duration) { + q.shift(); + } + }, observer.onError.bind(observer), function () { + var now = scheduler.now(), res = []; + while (q.length > 0) { + var next = q.shift(); + if (now - next.interval <= duration) { + res.push(next.value); + } + } + + observer.onNext(res); + observer.onCompleted(); + }); + }); + }; + + /** + * Takes elements for the specified duration from the start of the observable source sequence, using the specified scheduler to run timers. + * + * @example + * 1 - res = source.takeWithTime(5000, [optional scheduler]); + * @description + * This operator accumulates a queue with a length enough to store elements received during the initial duration window. + * As more elements are received, elements older than the specified duration are taken from the queue and produced on the + * result sequence. This causes elements to be delayed with duration. + * @param {Number} duration Duration for taking elements from the start of the sequence. + * @param {Scheduler} scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. + * @returns {Observable} An observable sequence with the elements taken during the specified duration from the start of the source sequence. + */ + observableProto.takeWithTime = function (duration, scheduler) { + var source = this; + scheduler || (scheduler = timeoutScheduler); + return new AnonymousObservable(function (observer) { + var t = scheduler.scheduleWithRelative(duration, function () { + observer.onCompleted(); + }); + + return new CompositeDisposable(t, source.subscribe(observer)); + }); + }; + + /** + * Skips elements for the specified duration from the start of the observable source sequence, using the specified scheduler to run timers. + * + * @example + * 1 - res = source.skipWithTime(5000, [optional scheduler]); + * + * @description + * Specifying a zero value for duration doesn't guarantee no elements will be dropped from the start of the source sequence. + * This is a side-effect of the asynchrony introduced by the scheduler, where the action that causes callbacks from the source sequence to be forwarded + * may not execute immediately, despite the zero due time. + * + * Errors produced by the source sequence are always forwarded to the result sequence, even if the error occurs before the duration. + * @param {Number} duration Duration for skipping elements from the start of the sequence. + * @param {Scheduler} scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. + * @returns {Observable} An observable sequence with the elements skipped during the specified duration from the start of the source sequence. + */ + observableProto.skipWithTime = function (duration, scheduler) { + var source = this; + scheduler || (scheduler = timeoutScheduler); + return new AnonymousObservable(function (observer) { + var open = false, + t = scheduler.scheduleWithRelative(duration, function () { open = true; }), + d = source.subscribe(function (x) { + if (open) { + observer.onNext(x); + } + }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); + + return new CompositeDisposable(t, d); + }); + }; + + /** + * Skips elements from the observable source sequence until the specified start time, using the specified scheduler to run timers. + * Errors produced by the source sequence are always forwarded to the result sequence, even if the error occurs before the start time. + * + * @examples + * 1 - res = source.skipUntilWithTime(new Date(), [optional scheduler]); + * 2 - res = source.skipUntilWithTime(5000, [optional scheduler]); + * @param startTime Time to start taking elements from the source sequence. If this value is less than or equal to Date(), no elements will be skipped. + * @param scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. + * @returns {Observable} An observable sequence with the elements skipped until the specified start time. + */ + observableProto.skipUntilWithTime = function (startTime, scheduler) { + scheduler || (scheduler = timeoutScheduler); + var source = this, schedulerMethod = startTime instanceof Date ? + 'scheduleWithAbsolute' : + 'scheduleWithRelative'; + return new AnonymousObservable(function (observer) { + var open = false; + + return new CompositeDisposable( + scheduler[schedulerMethod](startTime, function () { open = true; }), + source.subscribe( + function (x) { open && observer.onNext(x); }, + observer.onError.bind(observer), + observer.onCompleted.bind(observer))); + }); + }; + + /** + * Takes elements for the specified duration until the specified end time, using the specified scheduler to run timers. + * + * @example + * 1 - res = source.takeUntilWithTime(new Date(), [optional scheduler]); + * 2 - res = source.takeUntilWithTime(5000, [optional scheduler]); + * @param {Number | Date} endTime Time to stop taking elements from the source sequence. If this value is less than or equal to new Date(), the result stream will complete immediately. + * @param {Scheduler} scheduler Scheduler to run the timer on. + * @returns {Observable} An observable sequence with the elements taken until the specified end time. + */ + observableProto.takeUntilWithTime = function (endTime, scheduler) { + scheduler || (scheduler = timeoutScheduler); + var source = this, schedulerMethod = endTime instanceof Date ? + 'scheduleWithAbsolute' : + 'scheduleWithRelative'; + return new AnonymousObservable(function (observer) { + return new CompositeDisposable(scheduler[schedulerMethod](endTime, function () { + observer.onCompleted(); + }), source.subscribe(observer)); + }); + }; + + /* + * Performs a exclusive waiting for the first to finish before subscribing to another observable. + * Observables that come in between subscriptions will be dropped on the floor. + * @returns {Observable} A exclusive observable with only the results that happen when subscribed. + */ + observableProto.exclusive = function () { + var sources = this; + return new AnonymousObservable(function (observer) { + var hasCurrent = false, + isStopped = false, + m = new SingleAssignmentDisposable(), + g = new CompositeDisposable(); + + g.add(m); + + m.setDisposable(sources.subscribe( + function (innerSource) { + if (!hasCurrent) { + hasCurrent = true; + + isPromise(innerSource) && (innerSource = observableFromPromise(innerSource)); + + var innerSubscription = new SingleAssignmentDisposable(); + g.add(innerSubscription); + + innerSubscription.setDisposable(innerSource.subscribe( + observer.onNext.bind(observer), + observer.onError.bind(observer), + function () { + g.remove(innerSubscription); + hasCurrent = false; + if (isStopped && g.length === 1) { + observer.onCompleted(); + } + })); + } + }, + observer.onError.bind(observer), + function () { + isStopped = true; + if (!hasCurrent && g.length === 1) { + observer.onCompleted(); + } + })); + + return g; + }); + }; + /* + * Performs a exclusive map waiting for the first to finish before subscribing to another observable. + * Observables that come in between subscriptions will be dropped on the floor. + * @param {Function} selector Selector to invoke for every item in the current subscription. + * @param {Any} [thisArg] An optional context to invoke with the selector parameter. + * @returns {Observable} An exclusive observable with only the results that happen when subscribed. + */ + observableProto.exclusiveMap = function (selector, thisArg) { + var sources = this; + return new AnonymousObservable(function (observer) { + var index = 0, + hasCurrent = false, + isStopped = true, + m = new SingleAssignmentDisposable(), + g = new CompositeDisposable(); + + g.add(m); + + m.setDisposable(sources.subscribe( + function (innerSource) { + + if (!hasCurrent) { + hasCurrent = true; + + innerSubscription = new SingleAssignmentDisposable(); + g.add(innerSubscription); + + isPromise(innerSource) && (innerSource = observableFromPromise(innerSource)); + + innerSubscription.setDisposable(innerSource.subscribe( + function (x) { + var result; + try { + result = selector.call(thisArg, x, index++, innerSource); + } catch (e) { + observer.onError(e); + return; + } + + observer.onNext(result); + }, + observer.onError.bind(observer), + function () { + g.remove(innerSubscription); + hasCurrent = false; + + if (isStopped && g.length === 1) { + observer.onCompleted(); + } + })); + } + }, + observer.onError.bind(observer), + function () { + isStopped = true; + if (g.length === 1 && !hasCurrent) { + observer.onCompleted(); + } + })); + return g; + }); + }; + /** Provides a set of extension methods for virtual time scheduling. */ + Rx.VirtualTimeScheduler = (function (_super) { + + function notImplemented() { + throw new Error('Not implemented'); + } + + function localNow() { + return this.toDateTimeOffset(this.clock); + } + + function scheduleNow(state, action) { + return this.scheduleAbsoluteWithState(state, this.clock, action); + } + + function scheduleRelative(state, dueTime, action) { + return this.scheduleRelativeWithState(state, this.toRelative(dueTime), action); + } + + function scheduleAbsolute(state, dueTime, action) { + return this.scheduleRelativeWithState(state, this.toRelative(dueTime - this.now()), action); + } + + function invokeAction(scheduler, action) { + action(); + return disposableEmpty; + } + + inherits(VirtualTimeScheduler, _super); + + /** + * Creates a new virtual time scheduler with the specified initial clock value and absolute time comparer. + * + * @constructor + * @param {Number} initialClock Initial value for the clock. + * @param {Function} comparer Comparer to determine causality of events based on absolute time. + */ + function VirtualTimeScheduler(initialClock, comparer) { + this.clock = initialClock; + this.comparer = comparer; + this.isEnabled = false; + this.queue = new PriorityQueue(1024); + _super.call(this, localNow, scheduleNow, scheduleRelative, scheduleAbsolute); + } + + var VirtualTimeSchedulerPrototype = VirtualTimeScheduler.prototype; + + /** + * Adds a relative time value to an absolute time value. + * @param {Number} absolute Absolute virtual time value. + * @param {Number} relative Relative virtual time value to add. + * @return {Number} Resulting absolute virtual time sum value. + */ + VirtualTimeSchedulerPrototype.add = notImplemented; + + /** + * Converts an absolute time to a number + * @param {Any} The absolute time. + * @returns {Number} The absolute time in ms + */ + VirtualTimeSchedulerPrototype.toDateTimeOffset = notImplemented; + + /** + * Converts the TimeSpan value to a relative virtual time value. + * @param {Number} timeSpan TimeSpan value to convert. + * @return {Number} Corresponding relative virtual time value. + */ + VirtualTimeSchedulerPrototype.toRelative = notImplemented; + + /** + * Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be emulated using recursive scheduling. + * @param {Mixed} state Initial state passed to the action upon the first iteration. + * @param {Number} period Period for running the work periodically. + * @param {Function} action Action to be executed, potentially updating the state. + * @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort). + */ + VirtualTimeSchedulerPrototype.schedulePeriodicWithState = function (state, period, action) { + var s = new SchedulePeriodicRecursive(this, state, period, action); + return s.start(); + }; + + /** + * Schedules an action to be executed after dueTime. + * @param {Mixed} state State passed to the action to be executed. + * @param {Number} dueTime Relative time after which to execute the action. + * @param {Function} action Action to be executed. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + VirtualTimeSchedulerPrototype.scheduleRelativeWithState = function (state, dueTime, action) { + var runAt = this.add(this.clock, dueTime); + return this.scheduleAbsoluteWithState(state, runAt, action); + }; + + /** + * Schedules an action to be executed at dueTime. + * @param {Number} dueTime Relative time after which to execute the action. + * @param {Function} action Action to be executed. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + VirtualTimeSchedulerPrototype.scheduleRelative = function (dueTime, action) { + return this.scheduleRelativeWithState(action, dueTime, invokeAction); + }; + + /** + * Starts the virtual time scheduler. + */ + VirtualTimeSchedulerPrototype.start = function () { + var next; + if (!this.isEnabled) { + this.isEnabled = true; + do { + next = this.getNext(); + if (next !== null) { + if (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 next; + var dueToClock = this.comparer(this.clock, time); + if (this.comparer(this.clock, time) > 0) { + throw new Error(argumentOutOfRange); + } + if (dueToClock === 0) { + return; + } + if (!this.isEnabled) { + this.isEnabled = true; + do { + next = this.getNext(); + if (next !== null && this.comparer(next.dueTime, time) <= 0) { + if (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); + var dueToClock = this.comparer(this.clock, dt); + if (dueToClock > 0) { + throw new Error(argumentOutOfRange); + } + if (dueToClock === 0) { + return; + } + this.advanceTo(dt); + }; + + /** + * Advances the scheduler's clock by the specified relative time. + * @param {Number} time Relative time to advance the scheduler's clock by. + */ + VirtualTimeSchedulerPrototype.sleep = function (time) { + var dt = this.add(this.clock, time); + + if (this.comparer(this.clock, dt) >= 0) { + throw new Error(argumentOutOfRange); + } + + this.clock = dt; + }; + + /** + * Gets the next scheduled item to be executed. + * @returns {ScheduledItem} The next scheduled item. + */ + VirtualTimeSchedulerPrototype.getNext = function () { + var next; + while (this.queue.length > 0) { + 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, + run = function (scheduler, state1) { + self.queue.remove(si); + return action(scheduler, state1); + }, + si = new ScheduledItem(self, state, run, dueTime, self.comparer); + self.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; + }; + + /** + * @private + */ + HistoricalSchedulerProto.toDateTimeOffset = function (absolute) { + return new Date(absolute).getTime(); + }; + + /** + * Converts the TimeSpan value to a relative virtual time value. + * + * @memberOf HistoricalScheduler + * @param {Number} timeSpan TimeSpan value to convert. + * @return {Number} Corresponding relative virtual time value. + */ + HistoricalSchedulerProto.toRelative = function (timeSpan) { + return timeSpan; + }; + + return HistoricalScheduler; + }(Rx.VirtualTimeScheduler)); + var AnonymousObservable = Rx.AnonymousObservable = (function (__super__) { + inherits(AnonymousObservable, __super__); + + // Fix subscriber to check for undefined or function returned to decorate as Disposable + function fixSubscriber(subscriber) { + if (typeof subscriber === 'undefined') { + subscriber = disposableEmpty; + } else if (typeof subscriber === 'function') { + subscriber = disposableCreate(subscriber); + } + + return subscriber; + } + + function AnonymousObservable(subscribe) { + if (!(this instanceof AnonymousObservable)) { + return new AnonymousObservable(subscribe); + } + + function s(observer) { + var setDisposable = function () { + try { + autoDetachObserver.setDisposable(fixSubscriber(subscribe(autoDetachObserver))); + } catch (e) { + if (!autoDetachObserver.fail(e)) { + throw e; + } + } + }; + + var autoDetachObserver = new AutoDetachObserver(observer); + if (currentThreadScheduler.scheduleRequired()) { + currentThreadScheduler.schedule(setDisposable); + } else { + setDisposable(); + } + + return autoDetachObserver; + } + + __super__.call(this, s); + } + + return AnonymousObservable; + + }(Observable)); + + /** @private */ + var AutoDetachObserver = (function (_super) { + inherits(AutoDetachObserver, _super); + + function AutoDetachObserver(observer) { + _super.call(this); + this.observer = observer; + this.m = new SingleAssignmentDisposable(); + } + + var AutoDetachObserverPrototype = AutoDetachObserver.prototype; + + AutoDetachObserverPrototype.next = function (value) { + var noError = false; + try { + this.observer.onNext(value); + noError = true; + } catch (e) { + throw e; + } finally { + if (!noError) { + this.dispose(); + } + } + }; + + AutoDetachObserverPrototype.error = function (exn) { + try { + this.observer.onError(exn); + } catch (e) { + throw e; + } finally { + this.dispose(); + } + }; + + AutoDetachObserverPrototype.completed = function () { + try { + this.observer.onCompleted(); + } catch (e) { + throw e; + } finally { + this.dispose(); + } + }; + + AutoDetachObserverPrototype.setDisposable = function (value) { this.m.setDisposable(value); }; + AutoDetachObserverPrototype.getDisposable = function (value) { return this.m.getDisposable(); }; + /* @private */ + AutoDetachObserverPrototype.disposable = function (value) { + return arguments.length ? this.getDisposable() : setDisposable(value); + }; + + AutoDetachObserverPrototype.dispose = function () { + _super.prototype.dispose.call(this); + this.m.dispose(); + }; + + return AutoDetachObserver; + }(AbstractObserver)); + + /** @private */ + var GroupedObservable = (function (_super) { + inherits(GroupedObservable, _super); + + function subscribe(observer) { + return this.underlyingObservable.subscribe(observer); + } + + /** + * @constructor + * @private + */ + function GroupedObservable(key, underlyingObservable, mergedDisposable) { + _super.call(this, subscribe); + this.key = key; + this.underlyingObservable = !mergedDisposable ? + underlyingObservable : + new AnonymousObservable(function (observer) { + return new CompositeDisposable(mergedDisposable.getDisposable(), underlyingObservable.subscribe(observer)); + }); + } + + return GroupedObservable; + }(Observable)); + + /** + * Represents an object that is both an observable sequence as well as an observer. + * Each notification is broadcasted to all subscribed observers. + */ + var Subject = Rx.Subject = (function (_super) { + function subscribe(observer) { + checkDisposed.call(this); + if (!this.isStopped) { + this.observers.push(observer); + return new InnerSubscription(this, observer); + } + if (this.exception) { + observer.onError(this.exception); + return disposableEmpty; + } + observer.onCompleted(); + return disposableEmpty; + } + + inherits(Subject, _super); + + /** + * Creates a subject. + * @constructor + */ + function Subject() { + _super.call(this, subscribe); + this.isDisposed = false, + this.isStopped = false, + this.observers = []; + } + + addProperties(Subject.prototype, Observer, { + /** + * Indicates whether the subject has observers subscribed to it. + * @returns {Boolean} Indicates whether the subject has observers subscribed to it. + */ + hasObservers: function () { + return this.observers.length > 0; + }, + /** + * Notifies all subscribed observers about the end of the sequence. + */ + onCompleted: function () { + checkDisposed.call(this); + if (!this.isStopped) { + var os = this.observers.slice(0); + this.isStopped = true; + for (var i = 0, len = os.length; i < len; i++) { + os[i].onCompleted(); + } + + this.observers = []; + } + }, + /** + * Notifies all subscribed observers about the exception. + * @param {Mixed} error The exception to send to all observers. + */ + onError: function (exception) { + checkDisposed.call(this); + if (!this.isStopped) { + var os = this.observers.slice(0); + this.isStopped = true; + this.exception = exception; + for (var i = 0, len = os.length; i < len; i++) { + os[i].onError(exception); + } + + this.observers = []; + } + }, + /** + * Notifies all subscribed observers about the arrival of the specified element in the sequence. + * @param {Mixed} value The value to send to all observers. + */ + onNext: function (value) { + checkDisposed.call(this); + if (!this.isStopped) { + var os = this.observers.slice(0); + for (var i = 0, len = os.length; i < len; i++) { + os[i].onNext(value); + } + } + }, + /** + * Unsubscribe all observers and release resources. + */ + dispose: function () { + this.isDisposed = true; + this.observers = null; + } + }); + + /** + * Creates a subject from the specified observer and observable. + * @param {Observer} observer The observer used to send messages to the subject. + * @param {Observable} observable The observable used to subscribe to messages sent from the subject. + * @returns {Subject} Subject implemented using the given observer and observable. + */ + Subject.create = function (observer, observable) { + return new AnonymousSubject(observer, observable); + }; + + return Subject; + }(Observable)); + + /** + * Represents the result of an asynchronous operation. + * The last value before the OnCompleted notification, or the error received through OnError, is sent to all subscribed observers. + */ + var AsyncSubject = Rx.AsyncSubject = (function (_super) { + + function subscribe(observer) { + checkDisposed.call(this); + + if (!this.isStopped) { + this.observers.push(observer); + return new InnerSubscription(this, observer); + } + + var ex = this.exception, + hv = this.hasValue, + v = this.value; + + if (ex) { + observer.onError(ex); + } else if (hv) { + observer.onNext(v); + observer.onCompleted(); + } else { + observer.onCompleted(); + } + + return disposableEmpty; + } + + inherits(AsyncSubject, _super); + + /** + * Creates a subject that can only receive one value and that value is cached for all future observations. + * @constructor + */ + function AsyncSubject() { + _super.call(this, subscribe); + + this.isDisposed = false; + this.isStopped = false; + this.value = null; + this.hasValue = false; + this.observers = []; + this.exception = null; + } + + addProperties(AsyncSubject.prototype, Observer, { + /** + * Indicates whether the subject has observers subscribed to it. + * @returns {Boolean} Indicates whether the subject has observers subscribed to it. + */ + hasObservers: function () { + checkDisposed.call(this); + return this.observers.length > 0; + }, + /** + * Notifies all subscribed observers about the end of the sequence, also causing the last received value to be sent out (if any). + */ + onCompleted: function () { + var o, i, len; + checkDisposed.call(this); + if (!this.isStopped) { + this.isStopped = true; + var os = this.observers.slice(0), + v = this.value, + hv = this.hasValue; + + if (hv) { + for (i = 0, len = os.length; i < len; i++) { + o = os[i]; + o.onNext(v); + o.onCompleted(); + } + } else { + for (i = 0, len = os.length; i < len; i++) { + os[i].onCompleted(); + } + } + + this.observers = []; + } + }, + /** + * Notifies all subscribed observers about the exception. + * @param {Mixed} error The exception to send to all observers. + */ + onError: function (exception) { + checkDisposed.call(this); + if (!this.isStopped) { + var os = this.observers.slice(0); + this.isStopped = true; + this.exception = exception; + + for (var i = 0, len = os.length; i < len; i++) { + os[i].onError(exception); + } + + this.observers = []; + } + }, + /** + * Sends a value to the subject. The last value received before successful termination will be sent to all subscribed and future observers. + * @param {Mixed} value The value to store in the subject. + */ + onNext: function (value) { + checkDisposed.call(this); + if (!this.isStopped) { + this.value = value; + this.hasValue = true; + } + }, + /** + * Unsubscribe all observers and release resources. + */ + dispose: function () { + this.isDisposed = true; + this.observers = null; + this.exception = null; + this.value = null; + } + }); + + return AsyncSubject; + }(Observable)); + + /** @private */ + var AnonymousSubject = (function (_super) { + inherits(AnonymousSubject, _super); + + function subscribe(observer) { + return this.observable.subscribe(observer); + } + + /** + * @private + * @constructor + */ + function AnonymousSubject(observer, observable) { + _super.call(this, subscribe); + this.observer = observer; + this.observable = observable; + } + + addProperties(AnonymousSubject.prototype, Observer, { + /** + * @private + * @memberOf AnonymousSubject# + */ + onCompleted: function () { + this.observer.onCompleted(); + }, + /** + * @private + * @memberOf AnonymousSubject# + */ + onError: function (exception) { + this.observer.onError(exception); + }, + /** + * @private + * @memberOf AnonymousSubject# + */ + onNext: function (value) { + this.observer.onNext(value); + } + }); + + return AnonymousSubject; + }(Observable)); + + if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) { + root.Rx = Rx; + + define(function() { + return Rx; + }); + } else if (freeExports && freeModule) { + // in Node.js or RingoJS + if (moduleExports) { + (freeModule.exports = Rx).Rx = Rx; + } else { + freeExports.Rx = Rx; + } + } else { + // in a browser or Rhino + root.Rx = Rx; + } +}.call(this)); \ No newline at end of file diff --git a/ajax/libs/rxjs/2.2.28/rx.all.min.js b/ajax/libs/rxjs/2.2.28/rx.all.min.js new file mode 100644 index 000000000..5a6a72059 --- /dev/null +++ b/ajax/libs/rxjs/2.2.28/rx.all.min.js @@ -0,0 +1,3 @@ +(function(t){function e(){if(this.isDisposed)throw Error(le)}function n(t){var e=typeof t;return t&&("function"==e||"object"==e)||!1}function r(t){var e=[];if(!n(t))return e;qe.nonEnumArgs&&t.length&&u(t)&&(t=Te.call(t));var r=qe.enumPrototypes&&"function"==typeof t,i=qe.enumErrorProps&&(t===Ne||t instanceof Error);for(var o in t)r&&"prototype"==o||i&&("message"==o||"name"==o)||e.push(o);if(qe.nonEnumShadows&&t!==Oe){var s=t.constructor,c=-1,a=We.length;if(t===(s&&s.prototype))var h=t===stringProto?De:t===Ne?we:Se.call(t),l=ke[h];for(;a>++c;)o=We[c],l&&l[o]||!_e.call(t,o)||e.push(o)}return e}function i(t,e,n){for(var r=-1,i=n(t),o=i.length;o>++r;){var s=i[r];if(e(t[s],s,t)===!1)break}return t}function o(t,e){return i(t,e,r)}function s(t){return"function"!=typeof t.toString&&"string"==typeof(t+"")}function u(t){return t&&"object"==typeof t?Se.call(t)==ve:!1}function c(t){return"function"==typeof t||!1}function a(e,n,r,i){if(e===n)return 0!==e||1/e==1/n;var h=typeof e,l=typeof n;if(e===e&&(null==e||null==n||"function"!=h&&"object"!=h&&"function"!=l&&"object"!=l))return!1;var f=Se.call(e),p=Se.call(n);if(f==ve&&(f=xe),p==ve&&(p=xe),f!=p)return!1;switch(f){case me:case ye:return+e==+n;case Ee:return e!=+e?n!=+n:0==e?1/e==1/n:e==+n;case Ce:case De:return e==n+""}var d=f==be;if(!d){if(f!=xe||!qe.nodeClass&&(s(e)||s(n)))return!1;var v=!qe.argsObject&&u(e)?Object:e.constructor,b=!qe.argsObject&&u(n)?Object:n.constructor;if(!(v==b||_e.call(e,"constructor")&&_e.call(n,"constructor")||c(v)&&v instanceof v&&c(b)&&b instanceof b||!("constructor"in e&&"constructor"in n)))return!1}r||(r=[]),i||(i=[]);for(var m=r.length;m--;)if(r[m]==e)return i[m]==n;var y=0;if(result=!0,r.push(e),i.push(n),d){if(m=e.length,y=n.length,result=y==m)for(;y--;){var w=n[y];if(!(result=a(e[y],w,r,i)))break}}else o(n,function(n,o,s){return _e.call(s,o)?(y++,result=_e.call(e,o)&&a(e[o],n,r,i)):t}),result&&o(e,function(e,n,r){return _e.call(r,n)?result=--y>-1:t});return r.pop(),i.pop(),result}function h(t,e){return 1===t.length&&Array.isArray(t[e])?t[e]:Te.call(t)}function l(t,e){for(var n=Array(t),r=0;t>r;r++)n[r]=e();return n}function f(t,e){this.scheduler=t,this.disposable=e,this.isDisposed=!1}function p(e,n){return new ur(function(r){var i=new Je,o=new Xe;return o.setDisposable(i),i.setDisposable(e.subscribe(r.onNext.bind(r),function(e){var i,s;try{s=n(e)}catch(u){return r.onError(u),t}ce(s)&&(s=_n(s)),i=new Je,o.setDisposable(i),i.setDisposable(s.subscribe(r))},r.onCompleted.bind(r))),o})}function d(e,n){var r=this;return new ur(function(i){var o=0,s=e.length;return r.subscribe(function(r){if(s>o){var u,c=e[o++];try{u=n(r,c)}catch(a){return i.onError(a),t}i.onNext(u)}else i.onCompleted()},i.onError.bind(i),i.onCompleted.bind(i))})}function v(t){return this.map(function(e,n){var r=t(e,n);return ce(r)?_n(r):r}).concatAll()}function b(t){return this.select(function(e,n){var r=t(e,n);return ce(r)?_n(r):r}).mergeObservable()}function m(e,n,r){return new ur(function(i){var o=!1,s=null,u=[];return e.subscribe(function(e){var c,a;try{a=n(e)}catch(h){return i.onError(h),t}if(c=0,o)try{c=r(a,s)}catch(l){return i.onError(l),t}else o=!0,s=a;c>0&&(s=a,u=[]),c>=0&&u.push(e)},i.onError.bind(i),function(){i.onNext(u),i.onCompleted()})})}function y(t){if(0===t.length)throw Error(ae);return t[0]}function w(e,n,r){return new ur(function(i){var o=0,s=n.length;return e.subscribe(function(e){var u=!1;try{s>o&&(u=r(e,n[o++]))}catch(c){return i.onError(c),t}u||(i.onNext(!1),i.onCompleted())},i.onError.bind(i),function(){i.onNext(o===s),i.onCompleted()})})}function g(t,e,n,r){if(0>e)throw Error(he);return new ur(function(i){var o=e;return t.subscribe(function(t){0===o&&(i.onNext(t),i.onCompleted()),o--},i.onError.bind(i),function(){n?(i.onNext(r),i.onCompleted()):i.onError(Error(he))})})}function E(t,e,n){return new ur(function(r){var i=n,o=!1;return t.subscribe(function(t){o?r.onError(Error("Sequence contains more than one element")):(i=t,o=!0)},r.onError.bind(r),function(){o||e?(r.onNext(i),r.onCompleted()):r.onError(Error(ae))})})}function x(t,e,n){return new ur(function(r){return t.subscribe(function(t){r.onNext(t),r.onCompleted()},r.onError.bind(r),function(){e?(r.onNext(n),r.onCompleted()):r.onError(Error(ae))})})}function C(t,e,n){return new ur(function(r){var i=n,o=!1;return t.subscribe(function(t){i=t,o=!0},r.onError.bind(r),function(){o||e?(r.onNext(i),r.onCompleted()):r.onError(Error(ae))})})}function D(e,n,r,i){return new ur(function(o){var s=0;return e.subscribe(function(u){var c;try{c=n.call(r,u,s,e)}catch(a){return o.onError(a),t}c?(o.onNext(i?s:u),o.onCompleted()):s++},o.onError.bind(o),function(){o.onNext(i?-1:t),o.onCompleted()})})}function S(t,e,n){if(t.addListener)return t.addListener(e,n),Qe(function(){t.removeListener(e,n)});if(t.addEventListener)return t.addEventListener(e,n,!1),Qe(function(){t.removeEventListener(e,n,!1)});throw Error("No listener found")}function _(t,e,n){var r=new Be;if("function"==typeof t.item&&"number"==typeof t.length)for(var i=0,o=t.length;o>i;i++)r.add(_(t.item(i),e,n));else t&&r.add(S(t,e,n));return r}function A(e,n,r){return new ur(function(i){function o(e,n){h[n]=e;var o;if(u[n]=!0,c||(c=u.every(ne))){try{o=r.apply(null,h)}catch(s){return i.onError(s),t}i.onNext(o)}else a&&i.onCompleted()}var s=2,u=[!1,!1],c=!1,a=!1,h=Array(s);return new Be(e.subscribe(function(t){o(t,0)},i.onError.bind(i),function(){a=!0,i.onCompleted()}),n.subscribe(function(t){o(t,1)},i.onError.bind(i)))})}function N(t){if(false&t)return 2===t;for(var e=Math.sqrt(t),n=3;e>=n;){if(0===t%n)return!1;n+=2}return!0}function O(t){var e,n,r;for(e=0;Xn.length>e;++e)if(n=Xn[e],n>=t)return n;for(r=1|t;Xn[Xn.length-1]>r;){if(N(r))return r;r+=2}return t}function R(t){var e=757602046;if(!t.length)return e;for(var n=0,r=t.length;r>n;n++){var i=t.charCodeAt(n);e=(e<<5)-e+i,e&=e}return e}function j(t){var e=668265261;return t=61^t^t>>>16,t+=t<<3,t^=t>>>4,t*=e,t^=t>>>15}function W(){return{key:null,value:null,next:0,hashCode:0}}function k(t,e){return t.groupJoin(this,e,function(){return Nn()},function(t,e){return e})}function q(t){var e=this;return new ur(function(n){var r=new hr,i=new Be,o=new Ze(i);return n.onNext(Le(r,o)),i.add(e.subscribe(function(t){r.onNext(t)},function(t){r.onError(t),n.onError(t)},function(){r.onCompleted(),n.onCompleted()})),i.add(t.subscribe(function(){r.onCompleted(),r=new hr,n.onNext(Le(r,o))},function(t){r.onError(t),n.onError(t)},function(){r.onCompleted(),n.onCompleted()})),o})}function P(e){var n=this;return new ur(function(r){var i,o=new Xe,s=new Be(o),u=new Ze(s),c=new hr;return r.onNext(Le(c,u)),s.add(n.subscribe(function(t){c.onNext(t)},function(t){c.onError(t),r.onError(t)},function(){c.onCompleted(),r.onCompleted()})),i=function(){var n,s;try{s=e()}catch(a){return r.onError(a),t}n=new Je,o.setDisposable(n),n.setDisposable(s.take(1).subscribe(ee,function(t){c.onError(t),r.onError(t)},function(){c.onCompleted(),c=new hr,r.onNext(Le(c,u)),i()}))},i(),u})}function T(e,n){return new dn(function(){return new pn(function(){return e()?{done:!1,value:n}:{done:!0,value:t}})})}function V(t){this.patterns=t}function z(t,e){this.expression=t,this.selector=e}function L(t,e,n){var r=t.get(e);if(!r){var i=new ir(e,n);return t.set(e,i),i}return r}function M(t,e,n){var r,i;for(this.joinObserverArray=t,this.onNext=e,this.onCompleted=n,this.joinObservers=new rr,r=0;this.joinObserverArray.length>r;r++)i=this.joinObserverArray[r],this.joinObservers.set(i,i)}function I(t,e){return new ur(function(n){return e.scheduleWithAbsolute(t,function(){n.onNext(0),n.onCompleted()})})}function F(t,e,n){var r=en(e);return new ur(function(e){var i=0,o=t;return n.scheduleRecursiveWithAbsolute(o,function(t){var s;r>0&&(s=n.now(),o+=r,s>=o&&(o=s+r)),e.onNext(i++),t(o)})})}function B(t,e){var n=en(t);return new ur(function(t){return e.scheduleWithRelative(n,function(){t.onNext(0),t.onCompleted()})})}function H(t,e,n){return t===e?new ur(function(t){return n.schedulePeriodicWithState(0,e,function(e){return t.onNext(e),e+1})}):An(function(){return F(n.now()+t,e,n)})}function U(t,e){var n=this;return new ur(function(r){var i,o=!1,s=new Xe,u=null,c=[],a=!1;return i=n.materialize().timestamp(e).subscribe(function(n){var i,h;"E"===n.value.kind?(c=[],c.push(n),u=n.value.exception,h=!a):(c.push({value:n.value,timestamp:n.timestamp+t}),h=!o,o=!0),h&&(null!==u?r.onError(u):(i=new Je,s.setDisposable(i),i.setDisposable(e.scheduleRecursiveWithRelative(t,function(t){var n,i,s,h;if(null===u){a=!0;do s=null,c.length>0&&0>=c[0].timestamp-e.now()&&(s=c.shift().value),null!==s&&s.accept(r);while(null!==s);h=!1,i=0,c.length>0?(h=!0,i=Math.max(0,c[0].timestamp-e.now())):o=!1,n=u,a=!1,null!==n?r.onError(n):h&&t(i)}}))))}),new Be(i,s)})}function Q(t,e){var n=this;return An(function(){var r=t-e.now();return U.call(n,r,e)})}function $(t,e){return new ur(function(n){function r(){s&&(s=!1,n.onNext(o)),i&&n.onCompleted()}var i,o,s;return new Be(t.subscribe(function(t){s=!0,o=t},n.onError.bind(n),function(){i=!0}),e.subscribe(r,n.onError.bind(n),r))})}var K={"boolean":!1,"function":!0,object:!0,number:!1,string:!1,undefined:!1},J=K[typeof window]&&window||this,X=K[typeof exports]&&exports&&!exports.nodeType&&exports,Z=K[typeof module]&&module&&!module.nodeType&&module,G=Z&&Z.exports===X&&X,Y=K[typeof global]&&global;!Y||Y.global!==Y&&Y.window!==Y||(J=Y);var te={internals:{},config:{Promise:J.Promise},helpers:{}},ee=te.helpers.noop=function(){},ne=te.helpers.identity=function(t){return t},re=(te.helpers.pluck=function(t){return function(e){return e[t]}},te.helpers.just=function(t){return function(){return t}},te.helpers.defaultNow=Date.now),ie=te.helpers.defaultComparer=function(t,e){return Pe(t,e)},oe=te.helpers.defaultSubComparer=function(t,e){return t>e?1:e>t?-1:0},se=te.helpers.defaultKeySerializer=function(t){return""+t},ue=te.helpers.defaultError=function(t){throw t},ce=te.helpers.isPromise=function(t){return!!t&&"function"==typeof t.then&&t.then!==te.Observable.prototype.then};te.helpers.asArray=function(){return Array.prototype.slice.call(arguments)},te.helpers.not=function(t){return!t};var ae="Sequence contains no elements.",he="Argument out of range",le="Object has been disposed",fe="object"==typeof Symbol&&Symbol.iterator||"_es6shim_iterator_";J.Set&&"function"==typeof(new J.Set)["@@iterator"]&&(fe="@@iterator");var pe,de={done:!0,value:t},ve="[object Arguments]",be="[object Array]",me="[object Boolean]",ye="[object Date]",we="[object Error]",ge="[object Function]",Ee="[object Number]",xe="[object Object]",Ce="[object RegExp]",De="[object String]",Se=Object.prototype.toString,_e=Object.prototype.hasOwnProperty,Ae=Se.call(arguments)==ve,Ne=Error.prototype,Oe=Object.prototype,Re=Oe.propertyIsEnumerable;try{pe=!(Se.call(document)==xe&&!({toString:0}+""))}catch(je){pe=!0}var We=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],ke={};ke[be]=ke[ye]=ke[Ee]={constructor:!0,toLocaleString:!0,toString:!0,valueOf:!0},ke[me]=ke[De]={constructor:!0,toString:!0,valueOf:!0},ke[we]=ke[ge]=ke[Ce]={constructor:!0,toString:!0},ke[xe]={constructor:!0};var qe={};(function(){var t=function(){this.x=1},e=[];t.prototype={valueOf:1,y:1};for(var n in new t)e.push(n);for(n in arguments);qe.enumErrorProps=Re.call(Ne,"message")||Re.call(Ne,"name"),qe.enumPrototypes=Re.call(t,"prototype"),qe.nonEnumArgs=0!=n,qe.nonEnumShadows=!/valueOf/.test(e)})(1),Ae||(u=function(t){return t&&"object"==typeof t?_e.call(t,"callee"):!1}),c(/x/)&&(c=function(t){return"function"==typeof t&&Se.call(t)==ge});var Pe=te.internals.isEqual=function(t,e){return a(t,e,[],[])},Te=Array.prototype.slice;({}).hasOwnProperty;var Ve=this.inherits=te.internals.inherits=function(t,e){function n(){this.constructor=t}n.prototype=e.prototype,t.prototype=new n},ze=te.internals.addProperties=function(t){for(var e=Te.call(arguments,1),n=0,r=e.length;r>n;n++){var i=e[n];for(var o in i)t[o]=i[o]}},Le=te.internals.addRef=function(t,e){return new ur(function(n){return new Be(e.getDisposable(),t.subscribe(n))})},Me=function(t,e){this.id=t,this.value=e};Me.prototype.compareTo=function(t){var e=this.value.compareTo(t.value);return 0===e&&(e=this.id-t.id),e};var Ie=te.internals.PriorityQueue=function(t){this.items=Array(t),this.length=0},Fe=Ie.prototype;Fe.isHigherPriority=function(t,e){return 0>this.items[t].compareTo(this.items[e])},Fe.percolate=function(t){if(!(t>=this.length||0>t)){var e=t-1>>1;if(!(0>e||e===t)&&this.isHigherPriority(t,e)){var n=this.items[t];this.items[t]=this.items[e],this.items[e]=n,this.percolate(e)}}},Fe.heapify=function(e){if(e===t&&(e=0),!(e>=this.length||0>e)){var n=2*e+1,r=2*e+2,i=e;if(this.length>n&&this.isHigherPriority(n,i)&&(i=n),this.length>r&&this.isHigherPriority(r,i)&&(i=r),i!==e){var o=this.items[e];this.items[e]=this.items[i],this.items[i]=o,this.heapify(i)}}},Fe.peek=function(){return this.items[0].value},Fe.removeAt=function(t){this.items[t]=this.items[--this.length],delete this.items[this.length],this.heapify()},Fe.dequeue=function(){var t=this.peek();return this.removeAt(0),t},Fe.enqueue=function(t){var e=this.length++;this.items[e]=new Me(Ie.count++,t),this.percolate(e)},Fe.remove=function(t){for(var e=0;this.length>e;e++)if(this.items[e].value===t)return this.removeAt(e),!0;return!1},Ie.count=0;var Be=te.CompositeDisposable=function(){this.disposables=h(arguments,0),this.isDisposed=!1,this.length=this.disposables.length},He=Be.prototype;He.add=function(t){this.isDisposed?t.dispose():(this.disposables.push(t),this.length++)},He.remove=function(t){var e=!1;if(!this.isDisposed){var n=this.disposables.indexOf(t);-1!==n&&(e=!0,this.disposables.splice(n,1),this.length--,t.dispose())}return e},He.dispose=function(){if(!this.isDisposed){this.isDisposed=!0;var t=this.disposables.slice(0);this.disposables=[],this.length=0;for(var e=0,n=t.length;n>e;e++)t[e].dispose()}},He.clear=function(){var t=this.disposables.slice(0);this.disposables=[],this.length=0;for(var e=0,n=t.length;n>e;e++)t[e].dispose()},He.contains=function(t){return-1!==this.disposables.indexOf(t)},He.toArray=function(){return this.disposables.slice(0)};var Ue=te.Disposable=function(t){this.isDisposed=!1,this.action=t||ee};Ue.prototype.dispose=function(){this.isDisposed||(this.action(),this.isDisposed=!0)};var Qe=Ue.create=function(t){return new Ue(t)},$e=Ue.empty={dispose:ee},Ke=function(){function t(t){this.isSingle=t,this.isDisposed=!1,this.current=null}var e=t.prototype;return e.getDisposable=function(){return this.current},e.setDisposable=function(t){if(this.current&&this.isSingle)throw Error("Disposable has already been assigned");var e,n=this.isDisposed;n||(e=this.current,this.current=t),e&&e.dispose(),n&&t&&t.dispose()},e.dispose=function(){var t;this.isDisposed||(this.isDisposed=!0,t=this.current,this.current=null),t&&t.dispose()},t}(),Je=te.SingleAssignmentDisposable=function(t){function e(){t.call(this,!0)}return Ve(e,t),e}(Ke),Xe=te.SerialDisposable=function(t){function e(){t.call(this,!1)}return Ve(e,t),e}(Ke),Ze=te.RefCountDisposable=function(){function t(t){this.disposable=t,this.disposable.count++,this.isInnerDisposed=!1}function e(t){this.underlyingDisposable=t,this.isDisposed=!1,this.isPrimaryDisposed=!1,this.count=0}return t.prototype.dispose=function(){this.disposable.isDisposed||this.isInnerDisposed||(this.isInnerDisposed=!0,this.disposable.count--,0===this.disposable.count&&this.disposable.isPrimaryDisposed&&(this.disposable.isDisposed=!0,this.disposable.underlyingDisposable.dispose()))},e.prototype.dispose=function(){this.isDisposed||this.isPrimaryDisposed||(this.isPrimaryDisposed=!0,0===this.count&&(this.isDisposed=!0,this.underlyingDisposable.dispose()))},e.prototype.getDisposable=function(){return this.isDisposed?$e:new t(this)},e}();f.prototype.dispose=function(){var t=this;this.scheduler.schedule(function(){t.isDisposed||(t.isDisposed=!0,t.disposable.dispose())})};var Ge=te.internals.ScheduledItem=function(t,e,n,r,i){this.scheduler=t,this.state=e,this.action=n,this.dueTime=r,this.comparer=i||oe,this.disposable=new Je};Ge.prototype.invoke=function(){this.disposable.setDisposable(this.invokeCore())},Ge.prototype.compareTo=function(t){return this.comparer(this.dueTime,t.dueTime)},Ge.prototype.isCancelled=function(){return this.disposable.isDisposed},Ge.prototype.invokeCore=function(){return this.action(this.scheduler,this.state)};var Ye,tn=te.Scheduler=function(){function t(t,e,n,r){this.now=t,this._schedule=e,this._scheduleRelative=n,this._scheduleAbsolute=r}function e(t,e){var n=e.first,r=e.second,i=new Be,o=function(e){r(e,function(e){var n=!1,r=!1,s=t.scheduleWithState(e,function(t,e){return n?i.remove(s):r=!0,o(e),$e});r||(i.add(s),n=!0)})};return o(n),i}function n(t,e,n){var r=e.first,i=e.second,o=new Be,s=function(e){i(e,function(e,r){var i=!1,u=!1,c=t[n].call(t,e,r,function(t,e){return i?o.remove(c):u=!0,s(e),$e});u||(o.add(c),i=!0)})};return s(r),o}function r(t,e){return e(),$e}var i=t.prototype;return i.catchException=i["catch"]=function(t){return new cn(this,t)},i.schedulePeriodic=function(t,e){return this.schedulePeriodicWithState(null,t,function(){e()})},i.schedulePeriodicWithState=function(t,e,n){var r=t,i=setInterval(function(){r=n(r)},e);return Qe(function(){clearInterval(i)})},i.schedule=function(t){return this._schedule(t,r)},i.scheduleWithState=function(t,e){return this._schedule(t,e)},i.scheduleWithRelative=function(t,e){return this._scheduleRelative(e,t,r)},i.scheduleWithRelativeAndState=function(t,e,n){return this._scheduleRelative(t,e,n)},i.scheduleWithAbsolute=function(t,e){return this._scheduleAbsolute(e,t,r)},i.scheduleWithAbsoluteAndState=function(t,e,n){return this._scheduleAbsolute(t,e,n)},i.scheduleRecursive=function(t){return this.scheduleRecursiveWithState(t,function(t,e){t(function(){e(t)})})},i.scheduleRecursiveWithState=function(t,n){return this.scheduleWithState({first:t,second:n},function(t,n){return e(t,n)})},i.scheduleRecursiveWithRelative=function(t,e){return this.scheduleRecursiveWithRelativeAndState(e,t,function(t,e){t(function(n){e(t,n)})})},i.scheduleRecursiveWithRelativeAndState=function(t,e,r){return this._scheduleRelative({first:t,second:r},e,function(t,e){return n(t,e,"scheduleWithRelativeAndState")})},i.scheduleRecursiveWithAbsolute=function(t,e){return this.scheduleRecursiveWithAbsoluteAndState(e,t,function(t,e){t(function(n){e(t,n)})})},i.scheduleRecursiveWithAbsoluteAndState=function(t,e,r){return this._scheduleAbsolute({first:t,second:r},e,function(t,e){return n(t,e,"scheduleWithAbsoluteAndState")})},t.now=re,t.normalize=function(t){return 0>t&&(t=0),t},t}(),en=tn.normalize,nn=te.internals.SchedulePeriodicRecursive=function(){function t(t,e){e(0,this._period);try{this._state=this._action(this._state)}catch(n){throw this._cancel.dispose(),n}}function e(t,e,n,r){this._scheduler=t,this._state=e,this._period=n,this._action=r}return e.prototype.start=function(){var e=new Je;return this._cancel=e,e.setDisposable(this._scheduler.scheduleRecursiveWithRelativeAndState(0,this._period,t.bind(this))),e},e}(),rn=tn.immediate=function(){function t(t,e){return e(this,t)}function e(t,e,n){for(var r=en(r);r-this.now()>0;);return n(this,t)}function n(t,e,n){return this.scheduleWithRelativeAndState(t,e-this.now(),n)}return new tn(re,t,e,n)}(),on=tn.currentThread=function(){function t(t){for(var e;t.length>0;)if(e=t.dequeue(),!e.isCancelled()){for(;e.dueTime-tn.now()>0;);e.isCancelled()||e.invoke()}}function e(t,e){return this.scheduleWithRelativeAndState(t,0,e)}function n(e,n,r){var o=this.now()+tn.normalize(n),s=new Ge(this,e,r,o);if(i)i.enqueue(s);else{i=new Ie(4),i.enqueue(s);try{t(i)}catch(u){throw u}finally{i=null}}return s.disposable}function r(t,e,n){return this.scheduleWithRelativeAndState(t,e-this.now(),n)}var i,o=new tn(re,e,n,r);return o.scheduleRequired=function(){return null===i},o.ensureTrampoline=function(t){return null===i?this.schedule(t):t()},o}(),sn=ee;(function(){function t(){if(!J.postMessage||J.importScripts)return!1;var t=!1,e=J.onmessage;return J.onmessage=function(){t=!0},J.postMessage("","*"),J.onmessage=e,t}function e(t){if("string"==typeof t.data&&t.data.substring(0,o.length)===o){var e=t.data.substring(o.length),n=s[e];n(),delete s[e]}}var n=RegExp("^"+(Se+"").replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/toString| for [^\]]+/g,".*?")+"$"),r="function"==typeof(r=Y&&G&&Y.setImmediate)&&!n.test(r)&&r,i="function"==typeof(i=Y&&G&&Y.clearImmediate)&&!n.test(i)&&i;if("undefined"!=typeof process&&"[object process]"==={}.toString.call(process))Ye=process.nextTick;else if("function"==typeof r)Ye=r,sn=i;else if(t()){var o="ms.rx.schedule"+Math.random(),s={},u=0;J.addEventListener?J.addEventListener("message",e,!1):J.attachEvent("onmessage",e,!1),Ye=function(t){var e=u++;s[e]=t,J.postMessage(o+e,"*")}}else if(J.MessageChannel){var c=new J.MessageChannel,a={},h=0;c.port1.onmessage=function(t){var e=t.data,n=a[e];n(),delete a[e]},Ye=function(t){var e=h++;a[e]=t,c.port2.postMessage(e)}}else"document"in J&&"onreadystatechange"in J.document.createElement("script")?Ye=function(t){var e=J.document.createElement("script");e.onreadystatechange=function(){t(),e.onreadystatechange=null,e.parentNode.removeChild(e),e=null},J.document.documentElement.appendChild(e)}:(Ye=function(t){return setTimeout(t,0)},sn=clearTimeout)})();var un=tn.timeout=function(){function t(t,e){var n=this,r=new Je,i=Ye(function(){r.isDisposed||r.setDisposable(e(n,t))});return new Be(r,Qe(function(){sn(i)}))}function e(t,e,n){var r=this,i=tn.normalize(e);if(0===i)return r.scheduleWithState(t,n);var o=new Je,s=setTimeout(function(){o.isDisposed||o.setDisposable(n(r,t))},i);return new Be(o,Qe(function(){clearTimeout(s)}))}function n(t,e,n){return this.scheduleWithRelativeAndState(t,e-this.now(),n)}return new tn(re,t,e,n)}(),cn=function(t){function e(){return this._scheduler.now()}function n(t,e){return this._scheduler.scheduleWithState(t,this._wrap(e))}function r(t,e,n){return this._scheduler.scheduleWithRelativeAndState(t,e,this._wrap(n))}function i(t,e,n){return this._scheduler.scheduleWithAbsoluteAndState(t,e,this._wrap(n))}function o(o,s){this._scheduler=o,this._handler=s,this._recursiveOriginal=null,this._recursiveWrapper=null,t.call(this,e,n,r,i)}return Ve(o,t),o.prototype._clone=function(t){return new o(t,this._handler)},o.prototype._wrap=function(t){var e=this;return function(n,r){try{return t(e._getRecursiveWrapper(n),r)}catch(i){if(!e._handler(i))throw i;return $e}}},o.prototype._getRecursiveWrapper=function(t){if(this._recursiveOriginal!==t){this._recursiveOriginal=t;var e=this._clone(t);e._recursiveOriginal=t,e._recursiveWrapper=e,this._recursiveWrapper=e}return this._recursiveWrapper},o.prototype.schedulePeriodicWithState=function(t,e,n){var r=this,i=!1,o=new Je;return o.setDisposable(this._scheduler.schedulePeriodicWithState(t,e,function(t){if(i)return null;try{return n(t)}catch(e){if(i=!0,!r._handler(e))throw e;return o.dispose(),null}})),o},o}(tn),an=te.Notification=function(){function t(t,e){this.hasValue=null==e?!1:e,this.kind=t}var e=t.prototype;return e.accept=function(t,e,n){return 1===arguments.length&&"object"==typeof t?this._acceptObservable(t):this._accept(t,e,n)},e.toObservable=function(t){var e=this;return t||(t=rn),new ur(function(n){return t.schedule(function(){e._acceptObservable(n),"N"===e.kind&&n.onCompleted()})})},t}(),hn=an.createOnNext=function(){function t(t){return t(this.value)}function e(t){return t.onNext(this.value)}function n(){return"OnNext("+this.value+")"}return function(r){var i=new an("N",!0);return i.value=r,i._accept=t,i._acceptObservable=e,i.toString=n,i}}(),ln=an.createOnError=function(){function t(t,e){return e(this.exception)}function e(t){return t.onError(this.exception)}function n(){return"OnError("+this.exception+")"}return function(r){var i=new an("E");return i.exception=r,i._accept=t,i._acceptObservable=e,i.toString=n,i}}(),fn=an.createOnCompleted=function(){function t(t,e,n){return n()}function e(t){return t.onCompleted()}function n(){return"OnCompleted()"}return function(){var r=new an("C");return r._accept=t,r._acceptObservable=e,r.toString=n,r}}(),pn=te.internals.Enumerator=function(t){this._next=t};pn.prototype.next=function(){return this._next()},pn.prototype[fe]=function(){return this};var dn=te.internals.Enumerable=function(t){this._iterator=t};dn.prototype[fe]=function(){return this._iterator()},dn.prototype.concat=function(){var e=this;return new ur(function(n){var r;try{r=e[fe]()}catch(i){return n.onError(),t}var o,s=new Xe,u=rn.scheduleRecursive(function(e){var i;if(!o){try{i=r.next()}catch(u){return n.onError(u),t}if(i.done)return n.onCompleted(),t;var c=i.value;ce(c)&&(c=_n(c));var a=new Je;s.setDisposable(a),a.setDisposable(c.subscribe(n.onNext.bind(n),n.onError.bind(n),function(){e()}))}});return new Be(s,u,Qe(function(){o=!0}))})},dn.prototype.catchException=function(){var e=this;return new ur(function(n){var r;try{r=e[fe]()}catch(i){return n.onError(),t}var o,s,u=new Xe,c=rn.scheduleRecursive(function(e){if(!o){var i;try{i=r.next()}catch(c){return n.onError(c),t}if(i.done)return s?n.onError(s):n.onCompleted(),t;var a=i.value;ce(a)&&(a=_n(a));var h=new Je;u.setDisposable(h),h.setDisposable(a.subscribe(n.onNext.bind(n),function(t){s=t,e()},n.onCompleted.bind(n)))}});return new Be(u,c,Qe(function(){o=!0}))})};var vn=dn.repeat=function(t,e){return null==e&&(e=-1),new dn(function(){var n=e;return new pn(function(){return 0===n?de:(n>0&&n--,{done:!1,value:t})})})},bn=dn.forEach=function(t,e,n){return e||(e=ne),new dn(function(){var r=-1;return new pn(function(){return++r0&&(e=!this.isAcquired,this.isAcquired=!0),e&&this.disposable.setDisposable(this.scheduler.scheduleRecursive(function(e){var r;if(!(n.queue.length>0))return n.isAcquired=!1,t;r=n.queue.shift();try{r()}catch(i){throw n.queue=[],n.hasFaulted=!0,i}e()}))},n.prototype.dispose=function(){e.prototype.dispose.call(this),this.disposable.dispose()},n}(gn),Dn=function(t){function e(){t.apply(this,arguments)}return Ve(e,t),e.prototype.next=function(e){t.prototype.next.call(this,e),this.ensureActive()},e.prototype.error=function(e){t.prototype.error.call(this,e),this.ensureActive()},e.prototype.completed=function(){t.prototype.completed.call(this),this.ensureActive()},e}(Cn),Sn=te.Observable=function(){function t(t){this._subscribe=t}return wn=t.prototype,wn.subscribe=wn.forEach=function(t,e,n){var r="object"==typeof t?t:yn(t,e,n);return this._subscribe(r)},t}();wn.observeOn=function(t){var e=this;return new ur(function(n){return e.subscribe(new Dn(t,n))})},wn.subscribeOn=function(t){var e=this;return new ur(function(n){var r=new Je,i=new Xe;return i.setDisposable(r),r.setDisposable(t.schedule(function(){i.setDisposable(new f(t,e.subscribe(n)))})),i})};var _n=Sn.fromPromise=function(t){return new ur(function(e){return t.then(function(t){e.onNext(t),e.onCompleted()},function(t){e.onError(t)}),function(){t&&t.abort&&t.abort()}})};wn.toPromise=function(t){if(t||(t=te.config.Promise),!t)throw Error("Promise type not provided nor in Rx.config.Promise");var e=this;return new t(function(t,n){var r,i=!1;e.subscribe(function(t){r=t,i=!0},function(t){n(t)},function(){i&&t(r)})})},wn.toArray=function(){var t=this;return new ur(function(e){var n=[];return t.subscribe(n.push.bind(n),e.onError.bind(e),function(){e.onNext(n),e.onCompleted()})})},Sn.create=Sn.createWithDisposable=function(t){return new ur(t)};var An=Sn.defer=function(t){return new ur(function(e){var n;try{n=t()}catch(r){return Wn(r).subscribe(e)}return ce(n)&&(n=_n(n)),n.subscribe(e)})},Nn=Sn.empty=function(t){return t||(t=rn),new ur(function(e){return t.schedule(function(){e.onCompleted()})})},On=Sn.fromArray=function(t,e){return e||(e=on),new ur(function(n){var r=0,i=t.length;return e.scheduleRecursive(function(e){i>r?(n.onNext(t[r++]),e()):n.onCompleted()})})};Sn.fromIterable=function(e,n){return n||(n=on),new ur(function(r){var i;try{i=e[fe]()}catch(o){return r.onError(o),t}return n.scheduleRecursive(function(e){var n;try{n=i.next()}catch(o){return r.onError(o),t}n.done?r.onCompleted():(r.onNext(n.value),e())})})},Sn.generate=function(e,n,r,i,o){return o||(o=on),new ur(function(s){var u=!0,c=e;return o.scheduleRecursive(function(e){var o,a;try{u?u=!1:c=r(c),o=n(c),o&&(a=i(c))}catch(h){return s.onError(h),t}o?(s.onNext(a),e()):s.onCompleted()})})},Sn.of=function(){for(var t=arguments.length,e=Array(t),n=0;t>n;n++)e[n]=arguments[n];return On(e)},Sn.ofWithScheduler=function(t){for(var e=arguments.length-1,n=Array(e),r=0;e>r;r++)n[r]=arguments[r+1];return On(n,t)};var Rn=Sn.never=function(){return new ur(function(){return $e})};Sn.range=function(t,e,n){return n||(n=on),new ur(function(r){return n.scheduleRecursiveWithState(0,function(n,i){e>n?(r.onNext(t+n),i(n+1)):r.onCompleted()})})},Sn.repeat=function(t,e,n){return n||(n=on),null==e&&(e=-1),jn(t,n).repeat(e)};var jn=Sn["return"]=Sn.returnValue=Sn.just=function(t,e){return e||(e=rn),new ur(function(n){return e.schedule(function(){n.onNext(t),n.onCompleted()})})},Wn=Sn["throw"]=Sn.throwException=function(t,e){return e||(e=rn),new ur(function(n){return e.schedule(function(){n.onError(t)})})};Sn.using=function(t,e){return new ur(function(n){var r,i,o=$e;try{r=t(),r&&(o=r),i=e(r)}catch(s){return new Be(Wn(s).subscribe(n),o)}return new Be(i.subscribe(n),o)})},wn.amb=function(t){var e=this;return new ur(function(n){function r(){o||(o=s,a.dispose())}function i(){o||(o=u,c.dispose())}var o,s="L",u="R",c=new Je,a=new Je; +return ce(t)&&(t=_n(t)),c.setDisposable(e.subscribe(function(t){r(),o===s&&n.onNext(t)},function(t){r(),o===s&&n.onError(t)},function(){r(),o===s&&n.onCompleted()})),a.setDisposable(t.subscribe(function(t){i(),o===u&&n.onNext(t)},function(t){i(),o===u&&n.onError(t)},function(){i(),o===u&&n.onCompleted()})),new Be(c,a)})},Sn.amb=function(){function t(t,e){return t.amb(e)}for(var e=Rn(),n=h(arguments,0),r=0,i=n.length;i>r;r++)e=t(e,n[r]);return e},wn["catch"]=wn.catchException=function(t){return"function"==typeof t?p(this,t):kn([this,t])};var kn=Sn.catchException=Sn["catch"]=function(){var t=h(arguments,0);return bn(t).catchException()};wn.combineLatest=function(){var t=Te.call(arguments);return Array.isArray(t[0])?t[0].unshift(this):t.unshift(this),qn.apply(this,t)};var qn=Sn.combineLatest=function(){var e=Te.call(arguments),n=e.pop();return Array.isArray(e[0])&&(e=e[0]),new ur(function(r){function i(e){var i;if(c[e]=!0,a||(a=c.every(ne))){try{i=n.apply(null,f)}catch(o){return r.onError(o),t}r.onNext(i)}else h.filter(function(t,n){return n!==e}).every(ne)&&r.onCompleted()}function o(t){h[t]=!0,h.every(ne)&&r.onCompleted()}for(var s=function(){return!1},u=e.length,c=l(u,s),a=!1,h=l(u,s),f=Array(u),p=Array(u),d=0;u>d;d++)(function(t){var n=e[t],s=new Je;ce(n)&&(n=_n(n)),s.setDisposable(n.subscribe(function(e){f[t]=e,i(t)},r.onError.bind(r),function(){o(t)})),p[t]=s})(d);return new Be(p)})};wn.concat=function(){var t=Te.call(arguments,0);return t.unshift(this),Pn.apply(this,t)};var Pn=Sn.concat=function(){var t=h(arguments,0);return bn(t).concat()};wn.concatObservable=wn.concatAll=function(){return this.merge(1)},wn.merge=function(t){if("number"!=typeof t)return Tn(this,t);var e=this;return new ur(function(n){var r=0,i=new Be,o=!1,s=[],u=function(t){var e=new Je;i.add(e),ce(t)&&(t=_n(t)),e.setDisposable(t.subscribe(n.onNext.bind(n),n.onError.bind(n),function(){var t;i.remove(e),s.length>0?(t=s.shift(),u(t)):(r--,o&&0===r&&n.onCompleted())}))};return i.add(e.subscribe(function(e){t>r?(r++,u(e)):s.push(e)},n.onError.bind(n),function(){o=!0,0===r&&n.onCompleted()})),i})};var Tn=Sn.merge=function(){var t,e;return arguments[0]?arguments[0].now?(t=arguments[0],e=Te.call(arguments,1)):(t=rn,e=Te.call(arguments,0)):(t=rn,e=Te.call(arguments,1)),Array.isArray(e[0])&&(e=e[0]),On(e,t).mergeObservable()};wn.mergeObservable=wn.mergeAll=function(){var t=this;return new ur(function(e){var n=new Be,r=!1,i=new Je;return n.add(i),i.setDisposable(t.subscribe(function(t){var i=new Je;n.add(i),ce(t)&&(t=_n(t)),i.setDisposable(t.subscribe(function(t){e.onNext(t)},e.onError.bind(e),function(){n.remove(i),r&&1===n.length&&e.onCompleted()}))},e.onError.bind(e),function(){r=!0,1===n.length&&e.onCompleted()})),n})},wn.onErrorResumeNext=function(t){if(!t)throw Error("Second observable is required");return Vn([this,t])};var Vn=Sn.onErrorResumeNext=function(){var t=h(arguments,0);return new ur(function(e){var n=0,r=new Xe,i=rn.scheduleRecursive(function(i){var o,s;t.length>n?(o=t[n++],ce(o)&&(o=_n(o)),s=new Je,r.setDisposable(s),s.setDisposable(o.subscribe(e.onNext.bind(e),function(){i()},function(){i()}))):e.onCompleted()});return new Be(r,i)})};wn.skipUntil=function(t){var e=this;return new ur(function(n){var r=!1,i=new Be(e.subscribe(function(t){r&&n.onNext(t)},n.onError.bind(n),function(){r&&n.onCompleted()}));ce(t)&&(t=_n(t));var o=new Je;return i.add(o),o.setDisposable(t.subscribe(function(){r=!0,o.dispose()},n.onError.bind(n),function(){o.dispose()})),i})},wn["switch"]=wn.switchLatest=function(){var t=this;return new ur(function(e){var n=!1,r=new Xe,i=!1,o=0,s=t.subscribe(function(t){var s=new Je,u=++o;n=!0,r.setDisposable(s),ce(t)&&(t=_n(t)),s.setDisposable(t.subscribe(function(t){o===u&&e.onNext(t)},function(t){o===u&&e.onError(t)},function(){o===u&&(n=!1,i&&e.onCompleted())}))},e.onError.bind(e),function(){i=!0,n||e.onCompleted()});return new Be(s,r)})},wn.takeUntil=function(t){var e=this;return new ur(function(n){return ce(t)&&(t=_n(t)),new Be(e.subscribe(n),t.subscribe(n.onCompleted.bind(n),n.onError.bind(n),ee))})},wn.zip=function(){if(Array.isArray(arguments[0]))return d.apply(this,arguments);var e=this,n=Te.call(arguments),r=n.pop();return n.unshift(e),new ur(function(i){function o(n){var o,s;if(c.every(function(t){return t.length>0})){try{s=c.map(function(t){return t.shift()}),o=r.apply(e,s)}catch(u){return i.onError(u),t}i.onNext(o)}else a.filter(function(t,e){return e!==n}).every(ne)&&i.onCompleted()}function s(t){a[t]=!0,a.every(function(t){return t})&&i.onCompleted()}for(var u=n.length,c=l(u,function(){return[]}),a=l(u,function(){return!1}),h=Array(u),f=0;u>f;f++)(function(t){var e=n[t],r=new Je;ce(e)&&(e=_n(e)),r.setDisposable(e.subscribe(function(e){c[t].push(e),o(t)},i.onError.bind(i),function(){s(t)})),h[t]=r})(f);return new Be(h)})},Sn.zip=function(){var t=Te.call(arguments,0),e=t.shift();return e.zip.apply(e,t)},Sn.zipArray=function(){var e=h(arguments,0);return new ur(function(n){function r(e){if(s.every(function(t){return t.length>0})){var r=s.map(function(t){return t.shift()});n.onNext(r)}else if(u.filter(function(t,n){return n!==e}).every(ne))return n.onCompleted(),t}function i(e){return u[e]=!0,u.every(ne)?(n.onCompleted(),t):t}for(var o=e.length,s=l(o,function(){return[]}),u=l(o,function(){return!1}),c=Array(o),a=0;o>a;a++)(function(t){c[t]=new Je,c[t].setDisposable(e[t].subscribe(function(e){s[t].push(e),r(t)},n.onError.bind(n),function(){i(t)}))})(a);var h=new Be(c);return h.add(Qe(function(){for(var t=0,e=s.length;e>t;t++)s[t]=[]})),h})},wn.asObservable=function(){var t=this;return new ur(function(e){return t.subscribe(e)})},wn.bufferWithCount=function(t,e){return"number"!=typeof e&&(e=t),this.windowWithCount(t,e).selectMany(function(t){return t.toArray()}).where(function(t){return t.length>0})},wn.dematerialize=function(){var t=this;return new ur(function(e){return t.subscribe(function(t){return t.accept(e)},e.onError.bind(e),e.onCompleted.bind(e))})},wn.distinctUntilChanged=function(e,n){var r=this;return e||(e=ne),n||(n=ie),new ur(function(i){var o,s=!1;return r.subscribe(function(r){var u,c=!1;try{u=e(r)}catch(a){return i.onError(a),t}if(s)try{c=n(o,u)}catch(a){return i.onError(a),t}s&&c||(s=!0,o=u,i.onNext(r))},i.onError.bind(i),i.onCompleted.bind(i))})},wn["do"]=wn.doAction=function(t,e,n){var r,i=this;return"function"==typeof t?r=t:(r=t.onNext.bind(t),e=t.onError.bind(t),n=t.onCompleted.bind(t)),new ur(function(t){return i.subscribe(function(e){try{r(e)}catch(n){t.onError(n)}t.onNext(e)},function(n){if(e){try{e(n)}catch(r){t.onError(r)}t.onError(n)}else t.onError(n)},function(){if(n){try{n()}catch(e){t.onError(e)}t.onCompleted()}else t.onCompleted()})})},wn["finally"]=wn.finallyAction=function(t){var e=this;return new ur(function(n){var r;try{r=e.subscribe(n)}catch(i){throw t(),i}return Qe(function(){try{r.dispose()}catch(e){throw e}finally{t()}})})},wn.ignoreElements=function(){var t=this;return new ur(function(e){return t.subscribe(ee,e.onError.bind(e),e.onCompleted.bind(e))})},wn.materialize=function(){var t=this;return new ur(function(e){return t.subscribe(function(t){e.onNext(hn(t))},function(t){e.onNext(ln(t)),e.onCompleted()},function(){e.onNext(fn()),e.onCompleted()})})},wn.repeat=function(t){return vn(this,t).concat()},wn.retry=function(t){return vn(this,t).catchException()},wn.scan=function(){var e,n,r=!1,i=this;return 2===arguments.length?(r=!0,e=arguments[0],n=arguments[1]):n=arguments[0],new ur(function(o){var s,u,c;return i.subscribe(function(i){try{c||(c=!0),s?u=n(u,i):(u=r?n(e,i):i,s=!0)}catch(a){return o.onError(a),t}o.onNext(u)},o.onError.bind(o),function(){!c&&r&&o.onNext(e),o.onCompleted()})})},wn.skipLast=function(t){var e=this;return new ur(function(n){var r=[];return e.subscribe(function(e){r.push(e),r.length>t&&n.onNext(r.shift())},n.onError.bind(n),n.onCompleted.bind(n))})},wn.startWith=function(){var t,e,n=0;return arguments.length&&"now"in Object(arguments[0])?(e=arguments[0],n=1):e=rn,t=Te.call(arguments,n),bn([On(t,e),this]).concat()},wn.takeLast=function(t,e){return this.takeLastBuffer(t).selectMany(function(t){return On(t,e)})},wn.takeLastBuffer=function(t){var e=this;return new ur(function(n){var r=[];return e.subscribe(function(e){r.push(e),r.length>t&&r.shift()},n.onError.bind(n),function(){n.onNext(r),n.onCompleted()})})},wn.windowWithCount=function(t,e){var n=this;if(0>=t)throw Error(he);if(1===arguments.length&&(e=t),0>=e)throw Error(he);return new ur(function(r){var i=new Je,o=new Ze(i),s=0,u=[],c=function(){var t=new hr;u.push(t),r.onNext(Le(t,o))};return c(),i.setDisposable(n.subscribe(function(n){for(var r,i=0,o=u.length;o>i;i++)u[i].onNext(n);var a=s-t+1;a>=0&&0===a%e&&(r=u.shift(),r.onCompleted()),s++,0===s%e&&c()},function(t){for(;u.length>0;)u.shift().onError(t);r.onError(t)},function(){for(;u.length>0;)u.shift().onCompleted();r.onCompleted()})),o})},wn.selectConcat=wn.concatMap=function(t,e){return e?this.concatMap(function(n,r){var i=t(n,r),o=ce(i)?_n(i):i;return o.map(function(t){return e(n,t,r)})}):"function"==typeof t?v.call(this,t):v.call(this,function(){return t})},wn.defaultIfEmpty=function(e){var n=this;return e===t&&(e=null),new ur(function(t){var r=!1;return n.subscribe(function(e){r=!0,t.onNext(e)},t.onError.bind(t),function(){r||t.onNext(e),t.onCompleted()})})},wn.distinct=function(e,n){var r=this;return e||(e=ne),n||(n=se),new ur(function(i){var o={};return r.subscribe(function(r){var s,u,c,a=!1;try{s=e(r),u=n(s)}catch(h){return i.onError(h),t}for(c in o)if(u===c){a=!0;break}a||(o[u]=null,i.onNext(r))},i.onError.bind(i),i.onCompleted.bind(i))})},wn.groupBy=function(t,e,n){return this.groupByUntil(t,e,function(){return Rn()},n)},wn.groupByUntil=function(e,n,r,i){var o=this;return n||(n=ne),i||(i=se),new ur(function(s){var u={},c=new Be,a=new Ze(c);return c.add(o.subscribe(function(o){var h,l,f,p,d,v,b,m,y,w;try{v=e(o),b=i(v)}catch(g){for(w in u)u[w].onError(g);return s.onError(g),t}p=!1;try{y=u[b],y||(y=new hr,u[b]=y,p=!0)}catch(g){for(w in u)u[w].onError(g);return s.onError(g),t}if(p){d=new ar(v,y,a),l=new ar(v,y);try{h=r(l)}catch(g){for(w in u)u[w].onError(g);return s.onError(g),t}s.onNext(d),m=new Je,c.add(m);var E=function(){b in u&&(delete u[b],y.onCompleted()),c.remove(m)};m.setDisposable(h.take(1).subscribe(ee,function(t){for(w in u)u[w].onError(t);s.onError(t)},function(){E()}))}try{f=n(o)}catch(g){for(w in u)u[w].onError(g);return s.onError(g),t}y.onNext(f)},function(t){for(var e in u)u[e].onError(t);s.onError(t)},function(){for(var t in u)u[t].onCompleted();s.onCompleted()})),a})},wn.select=wn.map=function(e,n){var r=this;return new ur(function(i){var o=0;return r.subscribe(function(s){var u;try{u=e.call(n,s,o++,r)}catch(c){return i.onError(c),t}i.onNext(u)},i.onError.bind(i),i.onCompleted.bind(i))})},wn.pluck=function(t){return this.select(function(e){return e[t]})},wn.selectMany=wn.flatMap=function(t,e){return e?this.selectMany(function(n,r){var i=t(n,r),o=ce(i)?_n(i):i;return o.select(function(t){return e(n,t,r)})}):"function"==typeof t?b.call(this,t):b.call(this,function(){return t})},wn.selectSwitch=wn.flatMapLatest=wn.switchMap=function(t,e){return this.select(t,e).switchLatest()},wn.skip=function(t){if(0>t)throw Error(he);var e=this;return new ur(function(n){var r=t;return e.subscribe(function(t){0>=r?n.onNext(t):r--},n.onError.bind(n),n.onCompleted.bind(n))})},wn.skipWhile=function(e,n){var r=this;return new ur(function(i){var o=0,s=!1;return r.subscribe(function(u){if(!s)try{s=!e.call(n,u,o++,r)}catch(c){return i.onError(c),t}s&&i.onNext(u)},i.onError.bind(i),i.onCompleted.bind(i))})},wn.take=function(t,e){if(0>t)throw Error(he);if(0===t)return Nn(e);var n=this;return new ur(function(e){var r=t;return n.subscribe(function(t){r>0&&(r--,e.onNext(t),0===r&&e.onCompleted())},e.onError.bind(e),e.onCompleted.bind(e))})},wn.takeWhile=function(e,n){var r=this;return new ur(function(i){var o=0,s=!0;return r.subscribe(function(u){if(s){try{s=e.call(n,u,o++,r)}catch(c){return i.onError(c),t}s?i.onNext(u):i.onCompleted()}},i.onError.bind(i),i.onCompleted.bind(i))})},wn.where=wn.filter=function(e,n){var r=this;return new ur(function(i){var o=0;return r.subscribe(function(s){var u;try{u=e.call(n,s,o++,r)}catch(c){return i.onError(c),t}u&&i.onNext(s)},i.onError.bind(i),i.onCompleted.bind(i))})},wn.finalValue=function(){var t=this;return new ur(function(e){var n,r=!1;return t.subscribe(function(t){r=!0,n=t},e.onError.bind(e),function(){r?(e.onNext(n),e.onCompleted()):e.onError(Error(ae))})})},wn.aggregate=function(){var t,e,n;return 2===arguments.length?(t=arguments[0],e=!0,n=arguments[1]):n=arguments[0],e?this.scan(t,n).startWith(t).finalValue():this.scan(n).finalValue()},wn.reduce=function(t){var e,n;return 2===arguments.length&&(n=!0,e=arguments[1]),n?this.scan(e,t).startWith(e).finalValue():this.scan(t).finalValue()},wn.some=wn.any=function(t,e){var n=this;return t?n.where(t,e).any():new ur(function(t){return n.subscribe(function(){t.onNext(!0),t.onCompleted()},t.onError.bind(t),function(){t.onNext(!1),t.onCompleted()})})},wn.isEmpty=function(){return this.any().select(function(t){return!t})},wn.every=wn.all=function(t,e){return this.where(function(e){return!t(e)},e).any().select(function(t){return!t})},wn.contains=function(t,e){return e||(e=ie),this.where(function(n){return e(n,t)}).any()},wn.count=function(t,e){return t?this.where(t,e).count():this.aggregate(0,function(t){return t+1})},wn.sum=function(t,e){return t?this.select(t,e).sum():this.aggregate(0,function(t,e){return t+e})},wn.minBy=function(t,e){return e||(e=oe),m(this,t,function(t,n){return-1*e(t,n)})},wn.min=function(t){return this.minBy(ne,t).select(function(t){return y(t)})},wn.maxBy=function(t,e){return e||(e=oe),m(this,t,e)},wn.max=function(t){return this.maxBy(ne,t).select(function(t){return y(t)})},wn.average=function(t,e){return t?this.select(t,e).average():this.scan({sum:0,count:0},function(t,e){return{sum:t.sum+e,count:t.count+1}}).finalValue().select(function(t){if(0===t.count)throw Error("The input sequence was empty");return t.sum/t.count})},wn.sequenceEqual=function(e,n){var r=this;return n||(n=ie),Array.isArray(e)?w(r,e,n):new ur(function(i){var o=!1,s=!1,u=[],c=[],a=r.subscribe(function(e){var r,o;if(c.length>0){o=c.shift();try{r=n(o,e)}catch(a){return i.onError(a),t}r||(i.onNext(!1),i.onCompleted())}else s?(i.onNext(!1),i.onCompleted()):u.push(e)},i.onError.bind(i),function(){o=!0,0===u.length&&(c.length>0?(i.onNext(!1),i.onCompleted()):s&&(i.onNext(!0),i.onCompleted()))});ce(e)&&(e=_n(e));var h=e.subscribe(function(e){var r,s;if(u.length>0){s=u.shift();try{r=n(s,e)}catch(a){return i.onError(a),t}r||(i.onNext(!1),i.onCompleted())}else o?(i.onNext(!1),i.onCompleted()):c.push(e)},i.onError.bind(i),function(){s=!0,0===c.length&&(u.length>0?(i.onNext(!1),i.onCompleted()):o&&(i.onNext(!0),i.onCompleted()))});return new Be(a,h)})},wn.elementAt=function(t){return g(this,t,!1)},wn.elementAtOrDefault=function(t,e){return g(this,t,!0,e)},wn.single=function(t,e){return t?this.where(t,e).single():E(this,!1)},wn.singleOrDefault=function(t,e,n){return t?this.where(t,n).singleOrDefault(null,e):E(this,!0,e)},wn.first=function(t,e){return t?this.where(t,e).first():x(this,!1)},wn.firstOrDefault=function(t,e){return t?this.where(t).firstOrDefault(null,e):x(this,!0,e)},wn.last=function(t,e){return t?this.where(t,e).last():C(this,!1)},wn.lastOrDefault=function(t,e,n){return t?this.where(t,n).lastOrDefault(null,e):C(this,!0,e)},wn.find=function(t,e){return D(this,t,e,!1)},wn.findIndex=function(t,e){return D(this,t,e,!0)},Sn.start=function(t,e,n){return zn(t,e,n)()};var zn=Sn.toAsync=function(e,n,r){return n||(n=un),function(){var i=arguments,o=new lr;return n.schedule(function(){var n;try{n=e.apply(r,i)}catch(s){return o.onError(s),t}o.onNext(n),o.onCompleted()}),o.asObservable()}};Sn.fromCallback=function(e,n,r,i){return n||(n=rn),function(){var o=Te.call(arguments,0);return new ur(function(s){return n.schedule(function(){function n(e){var n=e;if(i)try{n=i(arguments)}catch(r){return s.onError(r),t}else 1===n.length&&(n=n[0]);s.onNext(n),s.onCompleted()}o.push(n),e.apply(r,o)})})}},Sn.fromNodeCallback=function(e,n,r,i){return n||(n=rn),function(){var o=Te.call(arguments,0);return new ur(function(s){return n.schedule(function(){function n(e){if(e)return s.onError(e),t;var n=Te.call(arguments,1);if(i)try{n=i(n)}catch(r){return s.onError(r),t}else 1===n.length&&(n=n[0]);s.onNext(n),s.onCompleted()}o.push(n),e.apply(r,o)})})}};var Ln=J.angular&&angular.element?angular.element:J.jQuery?J.jQuery:J.Zepto?J.Zepto:null,Mn=!!J.Ember&&"function"==typeof J.Ember.addListener;Sn.fromEvent=function(e,n,r){if(Mn)return In(function(t){Ember.addListener(e,n,t)},function(t){Ember.removeListener(e,n,t)},r);if(Ln){var i=Ln(e);return In(function(t){i.on(n,t)},function(t){i.off(n,t)},r)}return new ur(function(i){return _(e,n,function(e){var n=e;if(r)try{n=r(arguments)}catch(o){return i.onError(o),t}i.onNext(n)})}).publish().refCount()};var In=Sn.fromEventPattern=function(e,n,r){return new ur(function(i){function o(e){var n=e;if(r)try{n=r(arguments)}catch(o){return i.onError(o),t}i.onNext(n)}var s=e(o);return Qe(function(){n&&n(o,s)})}).publish().refCount()};Sn.startAsync=function(t){var e;try{e=t()}catch(n){return Wn(n)}return _n(e)};var Fn=function(t){function e(t){var e=this.source.publish(),n=e.subscribe(t),r=$e,i=this.subject.distinctUntilChanged().subscribe(function(t){t?r=e.connect():(r.dispose(),r=$e)});return new Be(n,r,i)}function n(n,r){this.source=n,this.subject=r||new hr,this.isPaused=!0,t.call(this,e)}return Ve(n,t),n.prototype.pause=function(){this.isPaused!==!0&&(this.isPaused=!0,this.subject.onNext(!1))},n.prototype.resume=function(){this.isPaused!==!1&&(this.isPaused=!1,this.subject.onNext(!0))},n}(Sn);wn.pausable=function(t){return new Fn(this,t)};var Bn=function(t){function e(t){var e=[],n=!0,r=A(this.source,this.subject.distinctUntilChanged(),function(t,e){return{data:t,shouldFire:e}}).subscribe(function(r){if(r.shouldFire&&n&&t.onNext(r.data),r.shouldFire&&!n){for(;e.length>0;)t.onNext(e.shift());n=!0}else r.shouldFire||n?!r.shouldFire&&n&&(n=!1):e.push(r.data)},function(n){for(;e.length>0;)t.onNext(e.shift());t.onError(n)},function(){for(;e.length>0;)t.onNext(e.shift());t.onCompleted()});return this.subject.onNext(!1),r}function n(n,r){this.source=n,this.subject=r||new hr,this.isPaused=!0,t.call(this,e)}return Ve(n,t),n.prototype.pause=function(){this.isPaused!==!0&&(this.isPaused=!0,this.subject.onNext(!1))},n.prototype.resume=function(){this.isPaused!==!1&&(this.isPaused=!1,this.subject.onNext(!0))},n}(Sn);wn.pausableBuffered=function(t){return new Bn(this,t)},wn.controlled=function(t){return null==t&&(t=!0),new Hn(this,t)};var Hn=function(t){function e(t){return this.source.subscribe(t)}function n(n,r){t.call(this,e),this.subject=new Un(r),this.source=n.multicast(this.subject).refCount()}return Ve(n,t),n.prototype.request=function(t){return null==t&&(t=-1),this.subject.request(t)},n}(Sn),Un=te.ControlledSubject=function(t){function n(t){return this.subject.subscribe(t)}function r(e){null==e&&(e=!0),t.call(this,n),this.subject=new hr,this.enableQueue=e,this.queue=e?[]:null,this.requestedCount=0,this.requestedDisposable=$e,this.error=null,this.hasFailed=!1,this.hasCompleted=!1,this.controlledDisposable=$e}return Ve(r,t),ze(r.prototype,mn,{onCompleted:function(){e.call(this),this.hasCompleted=!0,this.enableQueue&&0!==this.queue.length||this.subject.onCompleted()},onError:function(t){e.call(this),this.hasFailed=!0,this.error=t,this.enableQueue&&0!==this.queue.length||this.subject.onError(t)},onNext:function(t){e.call(this);var n=!1;0===this.requestedCount?this.enableQueue&&this.queue.push(t):(-1!==this.requestedCount&&0===this.requestedCount--&&this.disposeCurrentRequest(),n=!0),n&&this.subject.onNext(t)},_processRequest:function(t){if(this.enableQueue){for(;this.queue.length>=t&&t>0;)this.subject.onNext(this.queue.shift()),t--;return 0!==this.queue.length?{numberOfItems:t,returnValue:!0}:{numberOfItems:t,returnValue:!1}}return this.hasFailed?(this.subject.onError(this.error),this.controlledDisposable.dispose(),this.controlledDisposable=$e):this.hasCompleted&&(this.subject.onCompleted(),this.controlledDisposable.dispose(),this.controlledDisposable=$e),{numberOfItems:t,returnValue:!1}},request:function(t){e.call(this),this.disposeCurrentRequest();var n=this,r=this._processRequest(t);return t=r.numberOfItems,r.returnValue?$e:(this.requestedCount=t,this.requestedDisposable=Qe(function(){n.requestedCount=0}),this.requestedDisposable)},disposeCurrentRequest:function(){this.requestedDisposable.dispose(),this.requestedDisposable=$e},dispose:function(){this.isDisposed=!0,this.error=null,this.subject.dispose(),this.requestedDisposable.dispose()}}),r}(Sn);wn.multicast=function(t,e){var n=this;return"function"==typeof t?new ur(function(r){var i=n.multicast(t());return new Be(e(i).subscribe(r),i.connect())}):new Jn(n,t)},wn.publish=function(t){return t?this.multicast(function(){return new hr},t):this.multicast(new hr)},wn.share=function(){return this.publish(null).refCount()},wn.publishLast=function(t){return t?this.multicast(function(){return new lr},t):this.multicast(new lr)},wn.publishValue=function(t,e){return 2===arguments.length?this.multicast(function(){return new $n(e)},t):this.multicast(new $n(t))},wn.shareValue=function(t){return this.publishValue(t).refCount()},wn.replay=function(t,e,n,r){return t?this.multicast(function(){return new Kn(e,n,r)},t):this.multicast(new Kn(e,n,r))},wn.shareReplay=function(t,e,n){return this.replay(null,t,e,n).refCount()};var Qn=function(t,e){this.subject=t,this.observer=e};Qn.prototype.dispose=function(){if(!this.subject.isDisposed&&null!==this.observer){var t=this.subject.observers.indexOf(this.observer);this.subject.observers.splice(t,1),this.observer=null}};var $n=te.BehaviorSubject=function(t){function n(t){if(e.call(this),!this.isStopped)return this.observers.push(t),t.onNext(this.value),new Qn(this,t);var n=this.exception;return n?t.onError(n):t.onCompleted(),$e}function r(e){t.call(this,n),this.value=e,this.observers=[],this.isDisposed=!1,this.isStopped=!1,this.exception=null}return Ve(r,t),ze(r.prototype,mn,{hasObservers:function(){return this.observers.length>0},onCompleted:function(){if(e.call(this),!this.isStopped){var t=this.observers.slice(0);this.isStopped=!0;for(var n=0,r=t.length;r>n;n++)t[n].onCompleted();this.observers=[]}},onError:function(t){if(e.call(this),!this.isStopped){var n=this.observers.slice(0);this.isStopped=!0,this.exception=t;for(var r=0,i=n.length;i>r;r++)n[r].onError(t);this.observers=[]}},onNext:function(t){if(e.call(this),!this.isStopped){this.value=t;for(var n=this.observers.slice(0),r=0,i=n.length;i>r;r++)n[r].onNext(t)}},dispose:function(){this.isDisposed=!0,this.observers=null,this.value=null,this.exception=null}}),r}(Sn),Kn=te.ReplaySubject=function(t){function n(t,e){this.subject=t,this.observer=e}function r(t){var r=new Cn(this.scheduler,t),i=new n(this,r);e.call(this),this._trim(this.scheduler.now()),this.observers.push(r);for(var o=this.q.length,s=0,u=this.q.length;u>s;s++)r.onNext(this.q[s].value);return this.hasError?(o++,r.onError(this.error)):this.isStopped&&(o++,r.onCompleted()),r.ensureActive(o),i}function i(e,n,i){this.bufferSize=null==e?Number.MAX_VALUE:e,this.windowSize=null==n?Number.MAX_VALUE:n,this.scheduler=i||on,this.q=[],this.observers=[],this.isStopped=!1,this.isDisposed=!1,this.hasError=!1,this.error=null,t.call(this,r)}return n.prototype.dispose=function(){if(this.observer.dispose(),!this.subject.isDisposed){var t=this.subject.observers.indexOf(this.observer);this.subject.observers.splice(t,1)}},Ve(i,t),ze(i.prototype,mn,{hasObservers:function(){return this.observers.length>0},_trim:function(t){for(;this.q.length>this.bufferSize;)this.q.shift();for(;this.q.length>0&&t-this.q[0].interval>this.windowSize;)this.q.shift()},onNext:function(t){var n;if(e.call(this),!this.isStopped){var r=this.scheduler.now();this.q.push({interval:r,value:t}),this._trim(r);for(var i=this.observers.slice(0),o=0,s=i.length;s>o;o++)n=i[o],n.onNext(t),n.ensureActive()}},onError:function(t){var n;if(e.call(this),!this.isStopped){this.isStopped=!0,this.error=t,this.hasError=!0;var r=this.scheduler.now();this._trim(r);for(var i=this.observers.slice(0),o=0,s=i.length;s>o;o++)n=i[o],n.onError(t),n.ensureActive();this.observers=[]}},onCompleted:function(){var t;if(e.call(this),!this.isStopped){this.isStopped=!0;var n=this.scheduler.now();this._trim(n);for(var r=this.observers.slice(0),i=0,o=r.length;o>i;i++)t=r[i],t.onCompleted(),t.ensureActive();this.observers=[]}},dispose:function(){this.isDisposed=!0,this.observers=null}}),i}(Sn),Jn=te.ConnectableObservable=function(t){function e(e,n){function r(t){return i.subject.subscribe(t)}var i={subject:n,source:e.asObservable(),hasSubscription:!1,subscription:null};this.connect=function(){return i.hasSubscription||(i.hasSubscription=!0,i.subscription=new Be(i.source.subscribe(i.subject),Qe(function(){i.hasSubscription=!1}))),i.subscription},t.call(this,r)}return Ve(e,t),e.prototype.connect=function(){return this.connect()},e.prototype.refCount=function(){var t=null,e=0,n=this;return new ur(function(r){var i,o;return e++,i=1===e,o=n.subscribe(r),i&&(t=n.connect()),Qe(function(){o.dispose(),e--,0===e&&t.dispose()})})},e}(Sn),Xn=[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],Zn="no such key",Gn="duplicate key",Yn=function(){var t=0;return function(e){if(null==e)throw Error(Zn);if("string"==typeof e)return R(e);if("number"==typeof e)return j(e);if("boolean"==typeof e)return e===!0?1:0;if(e instanceof Date)return e.getTime();if(e.getHashCode)return e.getHashCode();var n=17*t++;return e.getHashCode=function(){return n},n}}(),tr=function(t,e){if(0>t)throw Error("out of range");t>0&&this._initialize(t),this.comparer=e||ie,this.freeCount=0,this.size=0,this.freeList=-1};tr.prototype._initialize=function(t){var e,n=O(t);for(this.buckets=Array(n),this.entries=Array(n),e=0;n>e;e++)this.buckets[e]=-1,this.entries[e]=W();this.freeList=-1},tr.prototype.count=function(){return this.size},tr.prototype.add=function(t,e){return this._insert(t,e,!0)},tr.prototype._insert=function(e,n,r){this.buckets||this._initialize(0);for(var i,o=2147483647&Yn(e),s=o%this.buckets.length,u=this.buckets[s];u>=0;u=this.entries[u].next)if(this.entries[u].hashCode===o&&this.comparer(this.entries[u].key,e)){if(r)throw Error(Gn);return this.entries[u].value=n,t}this.freeCount>0?(i=this.freeList,this.freeList=this.entries[i].next,--this.freeCount):(this.size===this.entries.length&&(this._resize(),s=o%this.buckets.length),i=this.size,++this.size),this.entries[i].hashCode=o,this.entries[i].next=this.buckets[s],this.entries[i].key=e,this.entries[i].value=n,this.buckets[s]=i},tr.prototype._resize=function(){var t=O(2*this.size),e=Array(t);for(r=0;e.length>r;++r)e[r]=-1;var n=Array(t);for(r=0;this.size>r;++r)n[r]=this.entries[r];for(var r=this.size;t>r;++r)n[r]=W();for(var i=0;this.size>i;++i){var o=n[i].hashCode%t;n[i].next=e[o],e[o]=i}this.buckets=e,this.entries=n},tr.prototype.remove=function(t){if(this.buckets)for(var e=2147483647&Yn(t),n=e%this.buckets.length,r=-1,i=this.buckets[n];i>=0;i=this.entries[i].next){if(this.entries[i].hashCode===e&&this.comparer(this.entries[i].key,t))return 0>r?this.buckets[n]=this.entries[i].next:this.entries[r].next=this.entries[i].next,this.entries[i].hashCode=-1,this.entries[i].next=this.freeList,this.entries[i].key=null,this.entries[i].value=null,this.freeList=i,++this.freeCount,!0;r=i}return!1},tr.prototype.clear=function(){var t,e;if(!(0>=this.size)){for(t=0,e=this.buckets.length;e>t;++t)this.buckets[t]=-1;for(t=0;this.size>t;++t)this.entries[t]=W();this.freeList=-1,this.size=0}},tr.prototype._findEntry=function(t){if(this.buckets)for(var e=2147483647&Yn(t),n=this.buckets[e%this.buckets.length];n>=0;n=this.entries[n].next)if(this.entries[n].hashCode===e&&this.comparer(this.entries[n].key,t))return n;return-1},tr.prototype.count=function(){return this.size-this.freeCount},tr.prototype.tryGetValue=function(e){var n=this._findEntry(e);return n>=0?this.entries[n].value:t},tr.prototype.getValues=function(){var t=0,e=[];if(this.entries)for(var n=0;this.size>n;n++)this.entries[n].hashCode>=0&&(e[t++]=this.entries[n].value);return e},tr.prototype.get=function(t){var e=this._findEntry(t);if(e>=0)return this.entries[e].value;throw Error(Zn)},tr.prototype.set=function(t,e){this._insert(t,e,!1)},tr.prototype.containskey=function(t){return this._findEntry(t)>=0},wn.join=function(e,n,r,i){var o=this;return new ur(function(s){var u=new Be,c=!1,a=0,h=new tr,l=!1,f=0,p=new tr;return u.add(o.subscribe(function(e){var r,o,l,f,d=a++,v=new Je;h.add(d,e),u.add(v),o=function(){return h.remove(d)&&0===h.count()&&c&&s.onCompleted(),u.remove(v)};try{r=n(e)}catch(b){return s.onError(b),t}v.setDisposable(r.take(1).subscribe(ee,s.onError.bind(s),function(){o()})),f=p.getValues();for(var m=0;f.length>m;m++){try{l=i(e,f[m])}catch(y){return s.onError(y),t}s.onNext(l)}},s.onError.bind(s),function(){c=!0,(l||0===h.count())&&s.onCompleted()})),u.add(e.subscribe(function(e){var n,o,c,a,d=f++,v=new Je;p.add(d,e),u.add(v),o=function(){return p.remove(d)&&0===p.count()&&l&&s.onCompleted(),u.remove(v)};try{n=r(e)}catch(b){return s.onError(b),t}v.setDisposable(n.take(1).subscribe(ee,s.onError.bind(s),function(){o()})),a=h.getValues();for(var m=0;a.length>m;m++){try{c=i(a[m],e)}catch(b){return s.onError(b),t}s.onNext(c)}},s.onError.bind(s),function(){l=!0,(c||0===p.count())&&s.onCompleted()})),u})},wn.groupJoin=function(e,n,r,i){var o=this;return new ur(function(s){var u=function(){},c=new Be,a=new Ze(c),h=new tr,l=new tr,f=0,p=0;return c.add(o.subscribe(function(e){var r=new hr,o=f++;h.add(o,r);var p,d,v,b,m;try{m=i(e,Le(r,a))}catch(y){for(v=h.getValues(),p=0,d=v.length;d>p;p++)v[p].onError(y);return s.onError(y),t}for(s.onNext(m),b=l.getValues(),p=0,d=b.length;d>p;p++)r.onNext(b[p]);var w=new Je;c.add(w);var g,E=function(){h.remove(o)&&r.onCompleted(),c.remove(w)};try{g=n(e)}catch(y){for(v=h.getValues(),p=0,d=h.length;d>p;p++)v[p].onError(y);return s.onError(y),t}w.setDisposable(g.take(1).subscribe(u,function(t){for(v=h.getValues(),p=0,d=v.length;d>p;p++)v[p].onError(t);s.onError(t)},E))},function(t){for(var e=h.getValues(),n=0,r=e.length;r>n;n++)e[n].onError(t);s.onError(t)},s.onCompleted.bind(s))),c.add(e.subscribe(function(e){var n,i,o,a=p++;l.add(a,e);var f=new Je;c.add(f);var d,v=function(){l.remove(a),c.remove(f)};try{d=r(e)}catch(b){for(n=h.getValues(),i=0,o=h.length;o>i;i++)n[i].onError(b);return s.onError(b),t}for(f.setDisposable(d.take(1).subscribe(u,function(t){for(n=h.getValues(),i=0,o=h.length;o>i;i++)n[i].onError(t);s.onError(t)},v)),n=h.getValues(),i=0,o=n.length;o>i;i++)n[i].onNext(e)},function(t){for(var e=h.getValues(),n=0,r=e.length;r>n;n++)e[n].onError(t);s.onError(t)})),a})},wn.buffer=function(){return this.window.apply(this,arguments).selectMany(function(t){return t.toArray()})},wn.window=function(t,e){return 1===arguments.length&&"function"!=typeof arguments[0]?q.call(this,t):"function"==typeof t?P.call(this,t):k.call(this,t,e)},wn.pairwise=function(){var t=this;return new ur(function(e){var n,r=!1;return t.subscribe(function(t){r?e.onNext([n,t]):r=!0,n=t},e.onError.bind(e),e.onCompleted.bind(e))})},wn.partition=function(t,e){var n=this.publish().refCount();return[n.filter(t,e),n.filter(function(n,r,i){return!t.call(e,n,r,i)})]},wn.letBind=wn.let=function(t){return t(this)},Sn["if"]=Sn.ifThen=function(t,e,n){return An(function(){return n||(n=Nn()),ce(e)&&(e=_n(e)),ce(n)&&(n=_n(n)),"function"==typeof n.now&&(n=Nn(n)),t()?e:n})},Sn["for"]=Sn.forIn=function(t,e){return bn(t,e).concat()};var er=Sn["while"]=Sn.whileDo=function(t,e){return ce(e)&&(e=_n(e)),T(t,e).concat()};wn.doWhile=function(t){return Pn([this,er(t,this)])},Sn["case"]=Sn.switchCase=function(t,e,n){return An(function(){n||(n=Nn()),"function"==typeof n.now&&(n=Nn(n)); +var r=e[t()];return ce(r)&&(r=_n(r)),r||n})},wn.expand=function(e,n){n||(n=rn);var r=this;return new ur(function(i){var o=[],s=new Xe,u=new Be(s),c=0,a=!1,h=function(){var r=!1;o.length>0&&(r=!a,a=!0),r&&s.setDisposable(n.scheduleRecursive(function(n){var r;if(!(o.length>0))return a=!1,t;r=o.shift();var s=new Je;u.add(s),s.setDisposable(r.subscribe(function(t){i.onNext(t);var n=null;try{n=e(t)}catch(r){i.onError(r)}o.push(n),c++,h()},i.onError.bind(i),function(){u.remove(s),c--,0===c&&i.onCompleted()})),n()}))};return o.push(r),c++,h(),u})},Sn.forkJoin=function(){var e=h(arguments,0);return new ur(function(n){var r=e.length;if(0===r)return n.onCompleted(),$e;for(var i=new Be,o=!1,s=Array(r),u=Array(r),c=Array(r),a=0;r>a;a++)(function(a){var h=e[a];ce(h)&&(h=_n(h)),i.add(h.subscribe(function(t){o||(s[a]=!0,c[a]=t)},function(t){o=!0,n.onError(t),i.dispose()},function(){if(!o){if(!s[a])return n.onCompleted(),t;u[a]=!0;for(var e=0;r>e;e++)if(!u[e])return;o=!0,n.onNext(c),n.onCompleted()}}))})(a);return i})},wn.forkJoin=function(e,n){var r=this;return new ur(function(i){var o,s,u=!1,c=!1,a=!1,h=!1,l=new Je,f=new Je;return ce(e)&&(e=_n(e)),l.setDisposable(r.subscribe(function(t){a=!0,o=t},function(t){f.dispose(),i.onError(t)},function(){if(u=!0,c)if(a)if(h){var e;try{e=n(o,s)}catch(r){return i.onError(r),t}i.onNext(e),i.onCompleted()}else i.onCompleted();else i.onCompleted()})),f.setDisposable(e.subscribe(function(t){h=!0,s=t},function(t){l.dispose(),i.onError(t)},function(){if(c=!0,u)if(a)if(h){var e;try{e=n(o,s)}catch(r){return i.onError(r),t}i.onNext(e),i.onCompleted()}else i.onCompleted();else i.onCompleted()})),new Be(l,f)})},wn.manySelect=function(t,e){e||(e=rn);var n=this;return An(function(){var r;return n.select(function(t){var e=new nr(t);return r&&r.onNext(t),r=e,e}).doAction(ee,function(t){r&&r.onError(t)},function(){r&&r.onCompleted()}).observeOn(e).select(function(e,n,r){return t(e,n,r)})})};var nr=function(t){function e(t){var e=this,n=new Be;return n.add(on.schedule(function(){t.onNext(e.head),n.add(e.tail.mergeObservable().subscribe(t))})),n}function n(n){t.call(this,e),this.head=n,this.tail=new lr}return Ve(n,t),ze(n.prototype,mn,{onCompleted:function(){this.onNext(Sn.empty())},onError:function(t){this.onNext(Sn.throwException(t))},onNext:function(t){this.tail.onNext(t),this.tail.onCompleted()}}),n}(Sn),rr=function(){function t(){this.keys=[],this.values=[]}return t.prototype["delete"]=function(t){var e=this.keys.indexOf(t);return-1!==e&&(this.keys.splice(e,1),this.values.splice(e,1)),-1!==e},t.prototype.get=function(t,e){var n=this.keys.indexOf(t);return-1!==n?this.values[n]:e},t.prototype.set=function(t,e){var n=this.keys.indexOf(t);-1!==n&&(this.values[n]=e),this.values[this.keys.push(t)-1]=e},t.prototype.size=function(){return this.keys.length},t.prototype.has=function(t){return-1!==this.keys.indexOf(t)},t.prototype.getKeys=function(){return this.keys.slice(0)},t.prototype.getValues=function(){return this.values.slice(0)},t}();V.prototype.and=function(t){var e=this.patterns.slice(0);return e.push(t),new V(e)},V.prototype.then=function(t){return new z(this,t)},z.prototype.activate=function(e,n,r){for(var i=this,o=[],s=0,u=this.expression.patterns.length;u>s;s++)o.push(L(e,this.expression.patterns[s],n.onError.bind(n)));var c=new M(o,function(){var e;try{e=i.selector.apply(i,arguments)}catch(r){return n.onError(r),t}n.onNext(e)},function(){for(var t=0,e=o.length;e>t;t++)o[t].removeActivePlan(c);r(c)});for(s=0,u=o.length;u>s;s++)o[s].addActivePlan(c);return c},M.prototype.dequeue=function(){for(var t=this.joinObservers.getValues(),e=0,n=t.length;n>e;e++)t[e].queue.shift()},M.prototype.match=function(){var t,e,n,r,i,o=!0;for(e=0,n=this.joinObserverArray.length;n>e;e++)if(0===this.joinObserverArray[e].queue.length){o=!1;break}if(o){for(t=[],r=!1,e=0,n=this.joinObserverArray.length;n>e;e++)t.push(this.joinObserverArray[e].queue[0]),"C"===this.joinObserverArray[e].queue[0].kind&&(r=!0);if(r)this.onCompleted();else{for(this.dequeue(),i=[],e=0;t.length>e;e++)i.push(t[e].value);this.onNext.apply(this,i)}}};var ir=function(e){function n(t,n){e.call(this),this.source=t,this.onError=n,this.queue=[],this.activePlans=[],this.subscription=new Je,this.isDisposed=!1}Ve(n,e);var r=n.prototype;return r.next=function(e){if(!this.isDisposed){if("E"===e.kind)return this.onError(e.exception),t;this.queue.push(e);for(var n=this.activePlans.slice(0),r=0,i=n.length;i>r;r++)n[r].match()}},r.error=ee,r.completed=ee,r.addActivePlan=function(t){this.activePlans.push(t)},r.subscribe=function(){this.subscription.setDisposable(this.source.materialize().subscribe(this))},r.removeActivePlan=function(t){var e=this.activePlans.indexOf(t);this.activePlans.splice(e,1),0===this.activePlans.length&&this.dispose()},r.dispose=function(){e.prototype.dispose.call(this),this.isDisposed||(this.isDisposed=!0,this.subscription.dispose())},n}(gn);wn.and=function(t){return new V([this,t])},wn.then=function(t){return new V([this]).then(t)},Sn.when=function(){var t=h(arguments,0);return new ur(function(e){var n,r,i,o,s,u,c=[],a=new rr;u=yn(e.onNext.bind(e),function(t){for(var n=a.getValues(),r=0,i=n.length;i>r;r++)n[r].onError(t);e.onError(t)},e.onCompleted.bind(e));try{for(r=0,i=t.length;i>r;r++)c.push(t[r].activate(a,u,function(t){var e=c.indexOf(t);c.splice(e,1),0===c.length&&u.onCompleted()}))}catch(h){Wn(h).subscribe(e)}for(n=new Be,s=a.getValues(),r=0,i=s.length;i>r;r++)o=s[r],o.subscribe(),n.add(o);return n})};var or=Sn.interval=function(t,e){return e||(e=un),H(t,t,e)},sr=Sn.timer=function(e,n,r){var i;return r||(r=un),n!==t&&"number"==typeof n?i=n:n!==t&&"object"==typeof n&&(r=n),e instanceof Date&&i===t?I(e.getTime(),r):e instanceof Date&&i!==t?(i=n,F(e.getTime(),i,r)):i===t?B(e,r):H(e,i,r)};wn.delay=function(t,e){return e||(e=un),t instanceof Date?Q.call(this,t.getTime(),e):U.call(this,t,e)},wn.throttle=function(t,e){return e||(e=un),this.throttleWithSelector(function(){return sr(t,e)})},wn.windowWithTime=function(e,n,r){var i,o=this;return n===t&&(i=e),r===t&&(r=un),"number"==typeof n?i=n:"object"==typeof n&&(i=e,r=n),new ur(function(t){function n(){var e=new Je,o=!1,s=!1;l.setDisposable(e),a===c?(o=!0,s=!0):c>a?o=!0:s=!0;var p=o?a:c,d=p-f;f=p,o&&(a+=i),s&&(c+=i),e.setDisposable(r.scheduleWithRelative(d,function(){var e;s&&(e=new hr,h.push(e),t.onNext(Le(e,u))),o&&(e=h.shift(),e.onCompleted()),n()}))}var s,u,c=i,a=e,h=[],l=new Xe,f=0;return s=new Be(l),u=new Ze(s),h.push(new hr),t.onNext(Le(h[0],u)),n(),s.add(o.subscribe(function(t){var e,n;for(e=0;h.length>e;e++)n=h[e],n.onNext(t)},function(e){var n,r;for(n=0;h.length>n;n++)r=h[n],r.onError(e);t.onError(e)},function(){var e,n;for(e=0;h.length>e;e++)n=h[e],n.onCompleted();t.onCompleted()})),u})},wn.windowWithTimeOrCount=function(t,e,n){var r=this;return n||(n=un),new ur(function(i){var o,s,u,c,a=0,h=new Xe,l=0;return s=new Be(h),u=new Ze(s),o=function(e){var r=new Je;h.setDisposable(r),r.setDisposable(n.scheduleWithRelative(t,function(){var t;e===l&&(a=0,t=++l,c.onCompleted(),c=new hr,i.onNext(Le(c,u)),o(t))}))},c=new hr,i.onNext(Le(c,u)),o(0),s.add(r.subscribe(function(t){var n=0,r=!1;c.onNext(t),a++,a===e&&(r=!0,a=0,n=++l,c.onCompleted(),c=new hr,i.onNext(Le(c,u))),r&&o(n)},function(t){c.onError(t),i.onError(t)},function(){c.onCompleted(),i.onCompleted()})),u})},wn.bufferWithTime=function(){return this.windowWithTime.apply(this,arguments).selectMany(function(t){return t.toArray()})},wn.bufferWithTimeOrCount=function(t,e,n){return this.windowWithTimeOrCount(t,e,n).selectMany(function(t){return t.toArray()})},wn.timeInterval=function(t){var e=this;return t||(t=un),An(function(){var n=t.now();return e.select(function(e){var r=t.now(),i=r-n;return n=r,{value:e,interval:i}})})},wn.timestamp=function(t){return t||(t=un),this.select(function(e){return{value:e,timestamp:t.now()}})},wn.sample=function(t,e){return e||(e=un),"number"==typeof t?$(this,or(t,e)):$(this,t)},wn.timeout=function(t,e,n){e||(e=Wn(Error("Timeout"))),n||(n=un);var r=this,i=t instanceof Date?"scheduleWithAbsolute":"scheduleWithRelative";return new ur(function(o){var s=0,u=new Je,c=new Xe,a=!1,h=new Xe;c.setDisposable(u);var l=function(){var r=s;h.setDisposable(n[i](t,function(){s===r&&(ce(e)&&(e=_n(e)),c.setDisposable(e.subscribe(o)))}))};return l(),u.setDisposable(r.subscribe(function(t){a||(s++,o.onNext(t),l())},function(t){a||(s++,o.onError(t))},function(){a||(s++,o.onCompleted())})),new Be(c,h)})},Sn.generateWithAbsoluteTime=function(e,n,r,i,o,s){return s||(s=un),new ur(function(u){var c,a,h=!0,l=!1,f=e;return s.scheduleRecursiveWithAbsolute(s.now(),function(e){l&&u.onNext(c);try{h?h=!1:f=r(f),l=n(f),l&&(c=i(f),a=o(f))}catch(s){return u.onError(s),t}l?e(a):u.onCompleted()})})},Sn.generateWithRelativeTime=function(e,n,r,i,o,s){return s||(s=un),new ur(function(u){var c,a,h=!0,l=!1,f=e;return s.scheduleRecursiveWithRelative(0,function(e){l&&u.onNext(c);try{h?h=!1:f=r(f),l=n(f),l&&(c=i(f),a=o(f))}catch(s){return u.onError(s),t}l?e(a):u.onCompleted()})})},wn.delaySubscription=function(t,e){return e||(e=un),this.delayWithSelector(sr(t,e),function(){return Nn()})},wn.delayWithSelector=function(e,n){var r,i,o=this;return"function"==typeof e?i=e:(r=e,i=n),new ur(function(e){var n=new Be,s=!1,u=function(){s&&0===n.length&&e.onCompleted()},c=new Xe,a=function(){c.setDisposable(o.subscribe(function(r){var o;try{o=i(r)}catch(s){return e.onError(s),t}var c=new Je;n.add(c),c.setDisposable(o.subscribe(function(){e.onNext(r),n.remove(c),u()},e.onError.bind(e),function(){e.onNext(r),n.remove(c),u()}))},e.onError.bind(e),function(){s=!0,c.dispose(),u()}))};return r?c.setDisposable(r.subscribe(function(){a()},e.onError.bind(e),function(){a()})):a(),new Be(c,n)})},wn.timeoutWithSelector=function(e,n,r){if(1===arguments.length){n=e;var e=Rn()}r||(r=Wn(Error("Timeout")));var i=this;return new ur(function(o){var s=new Xe,u=new Xe,c=new Je;s.setDisposable(c);var a=0,h=!1,l=function(t){var e=a,n=function(){return a===e},i=new Je;u.setDisposable(i),i.setDisposable(t.subscribe(function(){n()&&s.setDisposable(r.subscribe(o)),i.dispose()},function(t){n()&&o.onError(t)},function(){n()&&s.setDisposable(r.subscribe(o))}))};l(e);var f=function(){var t=!h;return t&&a++,t};return c.setDisposable(i.subscribe(function(e){if(f()){o.onNext(e);var r;try{r=n(e)}catch(i){return o.onError(i),t}l(r)}},function(t){f()&&o.onError(t)},function(){f()&&o.onCompleted()})),new Be(s,u)})},wn.throttleWithSelector=function(e){var n=this;return new ur(function(r){var i,o=!1,s=new Xe,u=0,c=n.subscribe(function(n){var c;try{c=e(n)}catch(a){return r.onError(a),t}o=!0,i=n,u++;var h=u,l=new Je;s.setDisposable(l),l.setDisposable(c.subscribe(function(){o&&u===h&&r.onNext(i),o=!1,l.dispose()},r.onError.bind(r),function(){o&&u===h&&r.onNext(i),o=!1,l.dispose()}))},function(t){s.dispose(),r.onError(t),o=!1,u++},function(){s.dispose(),o&&r.onNext(i),r.onCompleted(),o=!1,u++});return new Be(c,s)})},wn.skipLastWithTime=function(t,e){e||(e=un);var n=this;return new ur(function(r){var i=[];return n.subscribe(function(n){var o=e.now();for(i.push({interval:o,value:n});i.length>0&&o-i[0].interval>=t;)r.onNext(i.shift().value)},r.onError.bind(r),function(){for(var n=e.now();i.length>0&&n-i[0].interval>=t;)r.onNext(i.shift().value);r.onCompleted()})})},wn.takeLastWithTime=function(t,e,n){return this.takeLastBufferWithTime(t,e).selectMany(function(t){return On(t,n)})},wn.takeLastBufferWithTime=function(t,e){var n=this;return e||(e=un),new ur(function(r){var i=[];return n.subscribe(function(n){var r=e.now();for(i.push({interval:r,value:n});i.length>0&&r-i[0].interval>=t;)i.shift()},r.onError.bind(r),function(){for(var n=e.now(),o=[];i.length>0;){var s=i.shift();t>=n-s.interval&&o.push(s.value)}r.onNext(o),r.onCompleted()})})},wn.takeWithTime=function(t,e){var n=this;return e||(e=un),new ur(function(r){var i=e.scheduleWithRelative(t,function(){r.onCompleted()});return new Be(i,n.subscribe(r))})},wn.skipWithTime=function(t,e){var n=this;return e||(e=un),new ur(function(r){var i=!1,o=e.scheduleWithRelative(t,function(){i=!0}),s=n.subscribe(function(t){i&&r.onNext(t)},r.onError.bind(r),r.onCompleted.bind(r));return new Be(o,s)})},wn.skipUntilWithTime=function(t,e){e||(e=un);var n=this,r=t instanceof Date?"scheduleWithAbsolute":"scheduleWithRelative";return new ur(function(i){var o=!1;return new Be(e[r](t,function(){o=!0}),n.subscribe(function(t){o&&i.onNext(t)},i.onError.bind(i),i.onCompleted.bind(i)))})},wn.takeUntilWithTime=function(t,e){e||(e=un);var n=this,r=t instanceof Date?"scheduleWithAbsolute":"scheduleWithRelative";return new ur(function(i){return new Be(e[r](t,function(){i.onCompleted()}),n.subscribe(i))})},wn.exclusive=function(){var t=this;return new ur(function(e){var n=!1,r=!1,i=new Je,o=new Be;return o.add(i),i.setDisposable(t.subscribe(function(t){if(!n){n=!0,ce(t)&&(t=_n(t));var i=new Je;o.add(i),i.setDisposable(t.subscribe(e.onNext.bind(e),e.onError.bind(e),function(){o.remove(i),n=!1,r&&1===o.length&&e.onCompleted()}))}},e.onError.bind(e),function(){r=!0,n||1!==o.length||e.onCompleted()})),o})},wn.exclusiveMap=function(e,n){var r=this;return new ur(function(i){var o=0,s=!1,u=!0,c=new Je,a=new Be;return a.add(c),c.setDisposable(r.subscribe(function(r){s||(s=!0,innerSubscription=new Je,a.add(innerSubscription),ce(r)&&(r=_n(r)),innerSubscription.setDisposable(r.subscribe(function(s){var u;try{u=e.call(n,s,o++,r)}catch(c){return i.onError(c),t}i.onNext(u)},i.onError.bind(i),function(){a.remove(innerSubscription),s=!1,u&&1===a.length&&i.onCompleted()})))},i.onError.bind(i),function(){u=!0,1!==a.length||s||i.onCompleted()})),a})},te.VirtualTimeScheduler=function(t){function e(){throw Error("Not implemented")}function n(){return this.toDateTimeOffset(this.clock)}function r(t,e){return this.scheduleAbsoluteWithState(t,this.clock,e)}function i(t,e,n){return this.scheduleRelativeWithState(t,this.toRelative(e),n)}function o(t,e,n){return this.scheduleRelativeWithState(t,this.toRelative(e-this.now()),n)}function s(t,e){return e(),$e}function u(e,s){this.clock=e,this.comparer=s,this.isEnabled=!1,this.queue=new Ie(1024),t.call(this,n,r,i,o)}Ve(u,t);var c=u.prototype;return c.add=e,c.toDateTimeOffset=e,c.toRelative=e,c.schedulePeriodicWithState=function(t,e,n){var r=new nn(this,t,e,n);return r.start()},c.scheduleRelativeWithState=function(t,e,n){var r=this.add(this.clock,e);return this.scheduleAbsoluteWithState(t,r,n)},c.scheduleRelative=function(t,e){return this.scheduleRelativeWithState(e,t,s)},c.start=function(){var t;if(!this.isEnabled){this.isEnabled=!0;do t=this.getNext(),null!==t?(this.comparer(t.dueTime,this.clock)>0&&(this.clock=t.dueTime),t.invoke()):this.isEnabled=!1;while(this.isEnabled)}},c.stop=function(){this.isEnabled=!1},c.advanceTo=function(t){var e,n=this.comparer(this.clock,t);if(this.comparer(this.clock,t)>0)throw Error(he);if(0!==n&&!this.isEnabled){this.isEnabled=!0;do e=this.getNext(),null!==e&&0>=this.comparer(e.dueTime,t)?(this.comparer(e.dueTime,this.clock)>0&&(this.clock=e.dueTime),e.invoke()):this.isEnabled=!1;while(this.isEnabled);this.clock=t}},c.advanceBy=function(t){var e=this.add(this.clock,t),n=this.comparer(this.clock,e);if(n>0)throw Error(he);0!==n&&this.advanceTo(e)},c.sleep=function(t){var e=this.add(this.clock,t);if(this.comparer(this.clock,e)>=0)throw Error(he);this.clock=e},c.getNext=function(){for(var t;this.queue.length>0;){if(t=this.queue.peek(),!t.isCancelled())return t;this.queue.dequeue()}return null},c.scheduleAbsolute=function(t,e){return this.scheduleAbsoluteWithState(e,t,s)},c.scheduleAbsoluteWithState=function(t,e,n){var r=this,i=function(t,e){return r.queue.remove(o),n(t,e)},o=new Ge(r,t,i,e,r.comparer);return r.queue.enqueue(o),o.disposable},u}(tn),te.HistoricalScheduler=function(t){function e(e,n){var r=null==e?0:e,i=n||oe;t.call(this,r,i)}Ve(e,t);var n=e.prototype;return n.add=function(t,e){return t+e},n.toDateTimeOffset=function(t){return new Date(t).getTime()},n.toRelative=function(t){return t},e}(te.VirtualTimeScheduler);var ur=te.AnonymousObservable=function(e){function n(e){return e===t?e=$e:"function"==typeof e&&(e=Qe(e)),e}function r(i){function o(t){var e=function(){try{r.setDisposable(n(i(r)))}catch(t){if(!r.fail(t))throw t}},r=new cr(t);return on.scheduleRequired()?on.schedule(e):e(),r}return this instanceof r?(e.call(this,o),t):new r(i)}return Ve(r,e),r}(Sn),cr=function(t){function e(e){t.call(this),this.observer=e,this.m=new Je}Ve(e,t);var n=e.prototype;return n.next=function(t){var e=!1;try{this.observer.onNext(t),e=!0}catch(n){throw n}finally{e||this.dispose()}},n.error=function(t){try{this.observer.onError(t)}catch(e){throw e}finally{this.dispose()}},n.completed=function(){try{this.observer.onCompleted()}catch(t){throw t}finally{this.dispose()}},n.setDisposable=function(t){this.m.setDisposable(t)},n.getDisposable=function(){return this.m.getDisposable()},n.disposable=function(t){return arguments.length?this.getDisposable():setDisposable(t)},n.dispose=function(){t.prototype.dispose.call(this),this.m.dispose()},e}(gn),ar=function(t){function e(t){return this.underlyingObservable.subscribe(t)}function n(n,r,i){t.call(this,e),this.key=n,this.underlyingObservable=i?new ur(function(t){return new Be(i.getDisposable(),r.subscribe(t))}):r}return Ve(n,t),n}(Sn),hr=te.Subject=function(t){function n(t){return e.call(this),this.isStopped?this.exception?(t.onError(this.exception),$e):(t.onCompleted(),$e):(this.observers.push(t),new Qn(this,t))}function r(){t.call(this,n),this.isDisposed=!1,this.isStopped=!1,this.observers=[]}return Ve(r,t),ze(r.prototype,mn,{hasObservers:function(){return this.observers.length>0},onCompleted:function(){if(e.call(this),!this.isStopped){var t=this.observers.slice(0);this.isStopped=!0;for(var n=0,r=t.length;r>n;n++)t[n].onCompleted();this.observers=[]}},onError:function(t){if(e.call(this),!this.isStopped){var n=this.observers.slice(0);this.isStopped=!0,this.exception=t;for(var r=0,i=n.length;i>r;r++)n[r].onError(t);this.observers=[]}},onNext:function(t){if(e.call(this),!this.isStopped)for(var n=this.observers.slice(0),r=0,i=n.length;i>r;r++)n[r].onNext(t)},dispose:function(){this.isDisposed=!0,this.observers=null}}),r.create=function(t,e){return new fr(t,e)},r}(Sn),lr=te.AsyncSubject=function(t){function n(t){if(e.call(this),!this.isStopped)return this.observers.push(t),new Qn(this,t);var n=this.exception,r=this.hasValue,i=this.value;return n?t.onError(n):r?(t.onNext(i),t.onCompleted()):t.onCompleted(),$e}function r(){t.call(this,n),this.isDisposed=!1,this.isStopped=!1,this.value=null,this.hasValue=!1,this.observers=[],this.exception=null}return Ve(r,t),ze(r.prototype,mn,{hasObservers:function(){return e.call(this),this.observers.length>0},onCompleted:function(){var t,n,r;if(e.call(this),!this.isStopped){this.isStopped=!0;var i=this.observers.slice(0),o=this.value,s=this.hasValue;if(s)for(n=0,r=i.length;r>n;n++)t=i[n],t.onNext(o),t.onCompleted();else for(n=0,r=i.length;r>n;n++)i[n].onCompleted();this.observers=[]}},onError:function(t){if(e.call(this),!this.isStopped){var n=this.observers.slice(0);this.isStopped=!0,this.exception=t;for(var r=0,i=n.length;i>r;r++)n[r].onError(t);this.observers=[]}},onNext:function(t){e.call(this),this.isStopped||(this.value=t,this.hasValue=!0)},dispose:function(){this.isDisposed=!0,this.observers=null,this.exception=null,this.value=null}}),r}(Sn),fr=function(t){function e(t){return this.observable.subscribe(t)}function n(n,r){t.call(this,e),this.observer=n,this.observable=r}return Ve(n,t),ze(n.prototype,mn,{onCompleted:function(){this.observer.onCompleted()},onError:function(t){this.observer.onError(t)},onNext:function(t){this.observer.onNext(t)}}),n}(Sn);"function"==typeof define&&"object"==typeof define.amd&&define.amd?(J.Rx=te,define(function(){return te})):X&&Z?G?(Z.exports=te).Rx=te:X.Rx=te:J.Rx=te}).call(this); \ No newline at end of file diff --git a/ajax/libs/rxjs/2.2.28/rx.async.compat.js b/ajax/libs/rxjs/2.2.28/rx.async.compat.js new file mode 100644 index 000000000..68b1dfee8 --- /dev/null +++ b/ajax/libs/rxjs/2.2.28/rx.async.compat.js @@ -0,0 +1,397 @@ +// 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 (typeof define === 'function' && define.amd) { + define(['rx.binding', 'exports'], function (Rx, exports) { + root.Rx = factory(root, exports, Rx); + return root.Rx; + }); + } 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, + observableFromPromise = Observable.fromPromise, + observableThrow = Observable.throwException, + AnonymousObservable = Rx.AnonymousObservable, + AsyncSubject = Rx.AsyncSubject, + disposableCreate = Rx.Disposable.create, + CompositeDisposable= Rx.CompositeDisposable, + immediateScheduler = Rx.Scheduler.immediate, + timeoutScheduler = Rx.Scheduler.timeout, + slice = Array.prototype.slice; + + /** + * 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, scheduler, context) { + return observableToAsync(func, scheduler, context)(); + }; + + /** + * Converts the function into an asynchronous function. Each invocation of the resulting asynchronous function causes an invocation of the original synchronous function on the specified scheduler. + * + * @example + * var res = Rx.Observable.toAsync(function (x, y) { return x + y; })(4, 3); + * var res = Rx.Observable.toAsync(function (x, y) { return x + y; }, Rx.Scheduler.timeout)(4, 3); + * var res = Rx.Observable.toAsync(function (x) { this.log(x); }, Rx.Scheduler.timeout, console)('hello'); + * + * @param {Function} function Function to convert to an asynchronous function. + * @param {Scheduler} [scheduler] Scheduler to run the function on. If not specified, defaults to Scheduler.timeout. + * @param {Mixed} [context] The context for the func parameter to be executed. If not specified, defaults to undefined. + * @returns {Function} Asynchronous function. + */ + var observableToAsync = Observable.toAsync = function (func, scheduler, context) { + 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 {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. + * @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, scheduler, context, selector) { + scheduler || (scheduler = immediateScheduler); + return function () { + var args = slice.call(arguments, 0); + + return new AnonymousObservable(function (observer) { + return scheduler.schedule(function () { + function handler(e) { + var results = e; + + if (selector) { + try { + results = selector(arguments); + } catch (err) { + observer.onError(err); + return; + } + } else { + if (results.length === 1) { + results = results[0]; + } + } + + observer.onNext(results); + observer.onCompleted(); + } + + args.push(handler); + func.apply(context, args); + }); + }); + }; + }; + + /** + * Converts a Node.js callback style function to an observable sequence. This must be in function (err, ...) format. + * @param {Function} func The function to call + * @param {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. + * @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, scheduler, context, selector) { + scheduler || (scheduler = immediateScheduler); + return function () { + var args = slice.call(arguments, 0); + + return new AnonymousObservable(function (observer) { + return scheduler.schedule(function () { + + function handler(err) { + if (err) { + observer.onError(err); + return; + } + + var results = slice.call(arguments, 1); + + if (selector) { + try { + results = selector(results); + } catch (e) { + observer.onError(e); + return; + } + } else { + if (results.length === 1) { + results = results[0]; + } + } + + observer.onNext(results); + observer.onCompleted(); + } + + args.push(handler); + func.apply(context, args); + }); + }); + }; + }; + + function fixEvent(event) { + var stopPropagation = function () { + this.cancelBubble = true; + }; + + var preventDefault = function () { + this.bubbledKeyCode = this.keyCode; + if (this.ctrlKey) { + try { + this.keyCode = 0; + } catch (e) { } + } + this.defaultPrevented = true; + this.returnValue = false; + this.modified = true; + }; + + event || (event = root.event); + if (!event.target) { + event.target = event.target || event.srcElement; + + if (event.type == 'mouseover') { + event.relatedTarget = event.fromElement; + } + if (event.type == 'mouseout') { + event.relatedTarget = event.toElement; + } + // Adding stopPropogation and preventDefault to IE + if (!event.stopPropagation){ + event.stopPropagation = stopPropagation; + event.preventDefault = preventDefault; + } + // Normalize key events + switch(event.type){ + case 'keypress': + var c = ('charCode' in event ? event.charCode : event.keyCode); + if (c == 10) { + c = 0; + event.keyCode = 13; + } else if (c == 13 || c == 27) { + c = 0; + } else if (c == 3) { + c = 99; + } + event.charCode = c; + event.keyChar = event.charCode ? String.fromCharCode(event.charCode) : ''; + break; + } + } + + return event; + } + + function createListener (element, name, handler) { + // Node.js specific + if (element.addListener) { + element.addListener(name, handler); + return disposableCreate(function () { + element.removeListener(name, handler); + }); + } + // Standards compliant + if (element.addEventListener) { + element.addEventListener(name, handler, false); + return disposableCreate(function () { + element.removeEventListener(name, handler, false); + }); + } + if (element.attachEvent) { + // IE Specific + var innerHandler = function (event) { + handler(fixEvent(event)); + }; + element.attachEvent('on' + name, innerHandler); + return disposableCreate(function () { + element.detachEvent('on' + name, innerHandler); + }); + } + // Level 1 DOM Events + element['on' + name] = handler; + return disposableCreate(function () { + element['on' + name] = null; + }); + } + + function createEventListener (el, eventName, handler) { + var disposables = new CompositeDisposable(); + + // Asume NodeList + if (typeof el.item === 'function' && typeof el.length === 'number') { + 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; + } + + // Check for Angular/jQuery/Zepto support + var jq = + !!root.angular && !!angular.element ? angular.element : + (!!root.jQuery ? root.jQuery : ( + !!root.Zepto ? root.Zepto : null)); + + // Check for ember + var ember = !!root.Ember && typeof root.Ember.addListener === 'function'; + + /** + * 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) { + if (ember) { + return fromEventPattern( + function (h) { Ember.addListener(element, eventName, h); }, + function (h) { Ember.removeListener(element, eventName, h); }, + selector); + } + if (jq) { + var $elem = jq(element); + return fromEventPattern( + function (h) { $elem.on(eventName, h); }, + function (h) { $elem.off(eventName, h); }, + selector); + } + return new AnonymousObservable(function (observer) { + return createEventListener( + element, + eventName, + function handler (e) { + var results = e; + + if (selector) { + try { + results = selector(arguments); + } catch (err) { + observer.onError(err); + return + } + } + + observer.onNext(results); + }); + }).publish().refCount(); + }; + + /** + * Creates an observable sequence from an event emitter via an addHandler/removeHandler pair. + * @param {Function} addHandler The function to add a handler to the emitter. + * @param {Function} [removeHandler] The optional function to remove a handler from an emitter. + * @param {Function} [selector] A selector which takes the arguments from the event handler to produce a single item to yield on next. + * @returns {Observable} An observable sequence which wraps an event from an event emitter + */ + var fromEventPattern = Observable.fromEventPattern = function (addHandler, removeHandler, selector) { + return new AnonymousObservable(function (observer) { + function innerHandler (e) { + var result = e; + if (selector) { + try { + result = selector(arguments); + } catch (err) { + observer.onError(err); + return; + } + } + observer.onNext(result); + } + + var returnValue = addHandler(innerHandler); + return disposableCreate(function () { + if (removeHandler) { + removeHandler(innerHandler, returnValue); + } + }); + }).publish().refCount(); + }; + + /** + * Invokes the asynchronous function, surfacing the result through an observable sequence. + * @param {Function} functionAsync Asynchronous function which returns a Promise to run. + * @returns {Observable} An observable sequence exposing the function's result value, or an exception. + */ + Observable.startAsync = function (functionAsync) { + var promise; + try { + promise = functionAsync(); + } catch (e) { + return observableThrow(e); + } + return observableFromPromise(promise); + } + + return Rx; +})); \ No newline at end of file diff --git a/ajax/libs/rxjs/2.2.28/rx.async.compat.min.js b/ajax/libs/rxjs/2.2.28/rx.async.compat.min.js new file mode 100644 index 000000000..5353d1559 --- /dev/null +++ b/ajax/libs/rxjs/2.2.28/rx.async.compat.min.js @@ -0,0 +1 @@ +(function(t){var e={"boolean":!1,"function":!0,object:!0,number:!1,string:!1,undefined:!1},n=e[typeof window]&&window||this,r=e[typeof exports]&&exports&&!exports.nodeType&&exports,i=e[typeof module]&&module&&!module.nodeType&&module,o=(i&&i.exports===r&&r,e[typeof global]&&global);!o||o.global!==o&&o.window!==o||(n=o),"function"==typeof define&&define.amd?define(["rx.binding","exports"],function(e,r){return n.Rx=t(n,r,e),n.Rx}):"object"==typeof module&&module&&module.exports===r?module.exports=t(n,module.exports,require("./rx")):n.Rx=t(n,{},n.Rx)}).call(this,function(t,e,n){function r(e){var n=function(){this.cancelBubble=!0},r=function(){if(this.bubbledKeyCode=this.keyCode,this.ctrlKey)try{this.keyCode=0}catch(t){}this.defaultPrevented=!0,this.returnValue=!1,this.modified=!0};if(e||(e=t.event),!e.target)switch(e.target=e.target||e.srcElement,"mouseover"==e.type&&(e.relatedTarget=e.fromElement),"mouseout"==e.type&&(e.relatedTarget=e.toElement),e.stopPropagation||(e.stopPropagation=n,e.preventDefault=r),e.type){case"keypress":var i="charCode"in e?e.charCode:e.keyCode;10==i?(i=0,e.keyCode=13):13==i||27==i?i=0:3==i&&(i=99),e.charCode=i,e.keyChar=e.charCode?String.fromCharCode(e.charCode):""}return e}function i(t,e,n){if(t.addListener)return t.addListener(e,n),l(function(){t.removeListener(e,n)});if(t.addEventListener)return t.addEventListener(e,n,!1),l(function(){t.removeEventListener(e,n,!1)});if(t.attachEvent){var i=function(t){n(r(t))};return t.attachEvent("on"+e,i),l(function(){t.detachEvent("on"+e,i)})}return t["on"+e]=n,l(function(){t["on"+e]=null})}function o(t,e,n){var r=new f;if("function"==typeof t.item&&"number"==typeof t.length)for(var s=0,u=t.length;u>s;s++)r.add(o(t.item(s),e,n));else t&&r.add(i(t,e,n));return r}var s=n.Observable,u=(s.prototype,s.fromPromise),c=s.throwException,a=n.AnonymousObservable,h=n.AsyncSubject,l=n.Disposable.create,f=n.CompositeDisposable,p=n.Scheduler.immediate,d=n.Scheduler.timeout,v=Array.prototype.slice;s.start=function(t,e,n){return b(t,e,n)()};var b=s.toAsync=function(t,e,n){return e||(e=d),function(){var r=arguments,i=new h;return e.schedule(function(){var e;try{e=t.apply(n,r)}catch(o){return i.onError(o),undefined}i.onNext(e),i.onCompleted()}),i.asObservable()}};s.fromCallback=function(t,e,n,r){return e||(e=p),function(){var i=v.call(arguments,0);return new a(function(o){return e.schedule(function(){function e(t){var e=t;if(r)try{e=r(arguments)}catch(n){return o.onError(n),undefined}else 1===e.length&&(e=e[0]);o.onNext(e),o.onCompleted()}i.push(e),t.apply(n,i)})})}},s.fromNodeCallback=function(t,e,n,r){return e||(e=p),function(){var i=v.call(arguments,0);return new a(function(o){return e.schedule(function(){function e(t){if(t)return o.onError(t),undefined;var e=v.call(arguments,1);if(r)try{e=r(e)}catch(n){return o.onError(n),undefined}else 1===e.length&&(e=e[0]);o.onNext(e),o.onCompleted()}i.push(e),t.apply(n,i)})})}};var m=t.angular&&angular.element?angular.element:t.jQuery?t.jQuery:t.Zepto?t.Zepto:null,y=!!t.Ember&&"function"==typeof t.Ember.addListener;s.fromEvent=function(t,e,n){if(y)return w(function(n){Ember.addListener(t,e,n)},function(n){Ember.removeListener(t,e,n)},n);if(m){var r=m(t);return w(function(t){r.on(e,t)},function(t){r.off(e,t)},n)}return new a(function(r){return o(t,e,function(t){var e=t;if(n)try{e=n(arguments)}catch(i){return r.onError(i),undefined}r.onNext(e)})}).publish().refCount()};var w=s.fromEventPattern=function(t,e,n){return new a(function(r){function i(t){var e=t;if(n)try{e=n(arguments)}catch(i){return r.onError(i),undefined}r.onNext(e)}var o=t(i);return l(function(){e&&e(i,o)})}).publish().refCount()};return s.startAsync=function(t){var e;try{e=t()}catch(n){return c(n)}return u(e)},n}); \ No newline at end of file diff --git a/ajax/libs/rxjs/2.2.28/rx.async.js b/ajax/libs/rxjs/2.2.28/rx.async.js new file mode 100644 index 000000000..800aeca84 --- /dev/null +++ b/ajax/libs/rxjs/2.2.28/rx.async.js @@ -0,0 +1,329 @@ +// 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 (typeof define === 'function' && define.amd) { + define(['rx.binding', 'exports'], function (Rx, exports) { + root.Rx = factory(root, exports, Rx); + return root.Rx; + }); + } 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, + observableFromPromise = Observable.fromPromise, + observableThrow = Observable.throwException, + AnonymousObservable = Rx.AnonymousObservable, + AsyncSubject = Rx.AsyncSubject, + disposableCreate = Rx.Disposable.create, + CompositeDisposable= Rx.CompositeDisposable, + immediateScheduler = Rx.Scheduler.immediate, + timeoutScheduler = Rx.Scheduler.timeout, + slice = Array.prototype.slice; + + /** + * 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, scheduler, context) { + return observableToAsync(func, scheduler, context)(); + }; + + /** + * Converts the function into an asynchronous function. Each invocation of the resulting asynchronous function causes an invocation of the original synchronous function on the specified scheduler. + * + * @example + * var res = Rx.Observable.toAsync(function (x, y) { return x + y; })(4, 3); + * var res = Rx.Observable.toAsync(function (x, y) { return x + y; }, Rx.Scheduler.timeout)(4, 3); + * var res = Rx.Observable.toAsync(function (x) { this.log(x); }, Rx.Scheduler.timeout, console)('hello'); + * + * @param {Function} function Function to convert to an asynchronous function. + * @param {Scheduler} [scheduler] Scheduler to run the function on. If not specified, defaults to Scheduler.timeout. + * @param {Mixed} [context] The context for the func parameter to be executed. If not specified, defaults to undefined. + * @returns {Function} Asynchronous function. + */ + var observableToAsync = Observable.toAsync = function (func, scheduler, context) { + 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 {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. + * @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, scheduler, context, selector) { + scheduler || (scheduler = immediateScheduler); + return function () { + var args = slice.call(arguments, 0); + + return new AnonymousObservable(function (observer) { + return scheduler.schedule(function () { + function handler(e) { + var results = e; + + if (selector) { + try { + results = selector(arguments); + } catch (err) { + observer.onError(err); + return; + } + } else { + if (results.length === 1) { + results = results[0]; + } + } + + observer.onNext(results); + observer.onCompleted(); + } + + args.push(handler); + func.apply(context, args); + }); + }); + }; + }; + + /** + * Converts a Node.js callback style function to an observable sequence. This must be in function (err, ...) format. + * @param {Function} func The function to call + * @param {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. + * @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, scheduler, context, selector) { + scheduler || (scheduler = immediateScheduler); + return function () { + var args = slice.call(arguments, 0); + + return new AnonymousObservable(function (observer) { + return scheduler.schedule(function () { + + function handler(err) { + if (err) { + observer.onError(err); + return; + } + + var results = slice.call(arguments, 1); + + if (selector) { + try { + results = selector(results); + } catch (e) { + observer.onError(e); + return; + } + } else { + if (results.length === 1) { + results = results[0]; + } + } + + observer.onNext(results); + observer.onCompleted(); + } + + args.push(handler); + func.apply(context, args); + }); + }); + }; + }; + + function createListener (element, name, handler) { + // Node.js specific + if (element.addListener) { + element.addListener(name, handler); + return disposableCreate(function () { + element.removeListener(name, handler); + }); + } + if (element.addEventListener) { + element.addEventListener(name, handler, false); + return disposableCreate(function () { + element.removeEventListener(name, handler, false); + }); + } + throw new Error('No listener found'); + } + + function createEventListener (el, eventName, handler) { + var disposables = new CompositeDisposable(); + + // Asume NodeList + if (typeof el.item === 'function' && typeof el.length === 'number') { + 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; + } + + // Check for Angular/jQuery/Zepto support + var jq = + !!root.angular && !!angular.element ? angular.element : + (!!root.jQuery ? root.jQuery : ( + !!root.Zepto ? root.Zepto : null)); + + // Check for ember + var ember = !!root.Ember && typeof root.Ember.addListener === 'function'; + + /** + * 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) { + if (ember) { + return fromEventPattern( + function (h) { Ember.addListener(element, eventName, h); }, + function (h) { Ember.removeListener(element, eventName, h); }, + selector); + } + if (jq) { + var $elem = jq(element); + return fromEventPattern( + function (h) { $elem.on(eventName, h); }, + function (h) { $elem.off(eventName, h); }, + selector); + } + return new AnonymousObservable(function (observer) { + return createEventListener( + element, + eventName, + function handler (e) { + var results = e; + + if (selector) { + try { + results = selector(arguments); + } catch (err) { + observer.onError(err); + return + } + } + + observer.onNext(results); + }); + }).publish().refCount(); + }; + + /** + * Creates an observable sequence from an event emitter via an addHandler/removeHandler pair. + * @param {Function} addHandler The function to add a handler to the emitter. + * @param {Function} [removeHandler] The optional function to remove a handler from an emitter. + * @param {Function} [selector] A selector which takes the arguments from the event handler to produce a single item to yield on next. + * @returns {Observable} An observable sequence which wraps an event from an event emitter + */ + var fromEventPattern = Observable.fromEventPattern = function (addHandler, removeHandler, selector) { + return new AnonymousObservable(function (observer) { + function innerHandler (e) { + var result = e; + if (selector) { + try { + result = selector(arguments); + } catch (err) { + observer.onError(err); + return; + } + } + observer.onNext(result); + } + + var returnValue = addHandler(innerHandler); + return disposableCreate(function () { + if (removeHandler) { + removeHandler(innerHandler, returnValue); + } + }); + }).publish().refCount(); + }; + + /** + * Invokes the asynchronous function, surfacing the result through an observable sequence. + * @param {Function} functionAsync Asynchronous function which returns a Promise to run. + * @returns {Observable} An observable sequence exposing the function's result value, or an exception. + */ + Observable.startAsync = function (functionAsync) { + var promise; + try { + promise = functionAsync(); + } catch (e) { + return observableThrow(e); + } + return observableFromPromise(promise); + } + + return Rx; +})); \ No newline at end of file diff --git a/ajax/libs/rxjs/2.2.28/rx.async.min.js b/ajax/libs/rxjs/2.2.28/rx.async.min.js new file mode 100644 index 000000000..1349359b0 --- /dev/null +++ b/ajax/libs/rxjs/2.2.28/rx.async.min.js @@ -0,0 +1 @@ +(function(t){var e={"boolean":!1,"function":!0,object:!0,number:!1,string:!1,undefined:!1},n=e[typeof window]&&window||this,r=e[typeof exports]&&exports&&!exports.nodeType&&exports,i=e[typeof module]&&module&&!module.nodeType&&module,o=(i&&i.exports===r&&r,e[typeof global]&&global);!o||o.global!==o&&o.window!==o||(n=o),"function"==typeof define&&define.amd?define(["rx.binding","exports"],function(e,r){return n.Rx=t(n,r,e),n.Rx}):"object"==typeof module&&module&&module.exports===r?module.exports=t(n,module.exports,require("./rx")):n.Rx=t(n,{},n.Rx)}).call(this,function(t,e,n){function r(t,e,n){if(t.addListener)return t.addListener(e,n),h(function(){t.removeListener(e,n)});if(t.addEventListener)return t.addEventListener(e,n,!1),h(function(){t.removeEventListener(e,n,!1)});throw Error("No listener found")}function i(t,e,n){var o=new l;if("function"==typeof t.item&&"number"==typeof t.length)for(var s=0,u=t.length;u>s;s++)o.add(i(t.item(s),e,n));else t&&o.add(r(t,e,n));return o}var o=n.Observable,s=(o.prototype,o.fromPromise),u=o.throwException,c=n.AnonymousObservable,a=n.AsyncSubject,h=n.Disposable.create,l=n.CompositeDisposable,f=n.Scheduler.immediate,p=n.Scheduler.timeout,d=Array.prototype.slice;o.start=function(t,e,n){return v(t,e,n)()};var v=o.toAsync=function(t,e,n){return e||(e=p),function(){var r=arguments,i=new a;return e.schedule(function(){var e;try{e=t.apply(n,r)}catch(o){return i.onError(o),undefined}i.onNext(e),i.onCompleted()}),i.asObservable()}};o.fromCallback=function(t,e,n,r){return e||(e=f),function(){var i=d.call(arguments,0);return new c(function(o){return e.schedule(function(){function e(t){var e=t;if(r)try{e=r(arguments)}catch(n){return o.onError(n),undefined}else 1===e.length&&(e=e[0]);o.onNext(e),o.onCompleted()}i.push(e),t.apply(n,i)})})}},o.fromNodeCallback=function(t,e,n,r){return e||(e=f),function(){var i=d.call(arguments,0);return new c(function(o){return e.schedule(function(){function e(t){if(t)return o.onError(t),undefined;var e=d.call(arguments,1);if(r)try{e=r(e)}catch(n){return o.onError(n),undefined}else 1===e.length&&(e=e[0]);o.onNext(e),o.onCompleted()}i.push(e),t.apply(n,i)})})}};var b=t.angular&&angular.element?angular.element:t.jQuery?t.jQuery:t.Zepto?t.Zepto:null,m=!!t.Ember&&"function"==typeof t.Ember.addListener;o.fromEvent=function(t,e,n){if(m)return y(function(n){Ember.addListener(t,e,n)},function(n){Ember.removeListener(t,e,n)},n);if(b){var r=b(t);return y(function(t){r.on(e,t)},function(t){r.off(e,t)},n)}return new c(function(r){return i(t,e,function(t){var e=t;if(n)try{e=n(arguments)}catch(i){return r.onError(i),undefined}r.onNext(e)})}).publish().refCount()};var y=o.fromEventPattern=function(t,e,n){return new c(function(r){function i(t){var e=t;if(n)try{e=n(arguments)}catch(i){return r.onError(i),undefined}r.onNext(e)}var o=t(i);return h(function(){e&&e(i,o)})}).publish().refCount()};return o.startAsync=function(t){var e;try{e=t()}catch(n){return u(n)}return s(e)},n}); \ No newline at end of file diff --git a/ajax/libs/rxjs/2.2.28/rx.backpressure.js b/ajax/libs/rxjs/2.2.28/rx.backpressure.js new file mode 100644 index 000000000..9aec8e1b1 --- /dev/null +++ b/ajax/libs/rxjs/2.2.28/rx.backpressure.js @@ -0,0 +1,410 @@ +// 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 (typeof define === 'function' && define.amd) { + define(['rx', 'exports'], function (Rx, exports) { + root.Rx = factory(root, exports, Rx); + return root.Rx; + }); + } 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, + CompositeDisposable = Rx.CompositeDisposable, + 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, + identity = Rx.helpers.identity; + + var objectDisposed = 'Object has been disposed'; + function checkDisposed() { if (this.isDisposed) { throw new Error(objectDisposed); } } + + var PausableObservable = (function (_super) { + + inherits(PausableObservable, _super); + + function subscribe(observer) { + var conn = this.source.publish(), + subscription = conn.subscribe(observer), + connection = disposableEmpty; + + var pausable = this.subject.distinctUntilChanged().subscribe(function (b) { + if (b) { + connection = conn.connect(); + } else { + connection.dispose(); + connection = disposableEmpty; + } + }); + + return new CompositeDisposable(subscription, connection, pausable); + } + + function PausableObservable(source, subject) { + this.source = source; + this.subject = subject || new Subject(); + this.isPaused = true; + _super.call(this, subscribe); + } + + PausableObservable.prototype.pause = function () { + if (this.isPaused === true){ + return; + } + this.isPaused = true; + this.subject.onNext(false); + }; + + PausableObservable.prototype.resume = function () { + if (this.isPaused === false){ + return; + } + this.isPaused = false; + this.subject.onNext(true); + }; + + return PausableObservable; + + }(Observable)); + + /** + * Pauses the underlying observable sequence based upon the observable sequence which yields true/false. + * @example + * var pauser = new Rx.Subject(); + * var source = Rx.Observable.interval(100).pausable(pauser); + * @param {Observable} pauser The observable sequence used to pause the underlying sequence. + * @returns {Observable} The observable sequence which is paused based upon the pauser. + */ + observableProto.pausable = function (pauser) { + return new PausableObservable(this, pauser); + }; + function combineLatestSource(source, subject, resultSelector) { + return new AnonymousObservable(function (observer) { + var n = 2, + hasValue = [false, false], + hasValueAll = false, + isDone = false, + values = new Array(n); + + function next(x, i) { + values[i] = x + var res; + hasValue[i] = true; + if (hasValueAll || (hasValueAll = hasValue.every(identity))) { + try { + res = resultSelector.apply(null, values); + } catch (ex) { + observer.onError(ex); + return; + } + observer.onNext(res); + } else if (isDone) { + observer.onCompleted(); + } + } + + return new CompositeDisposable( + source.subscribe( + function (x) { + next(x, 0); + }, + observer.onError.bind(observer), + function () { + isDone = true; + observer.onCompleted(); + }), + subject.subscribe( + function (x) { + next(x, 1); + }, + observer.onError.bind(observer)) + ); + }); + } + + var PausableBufferedObservable = (function (_super) { + + inherits(PausableBufferedObservable, _super); + + function subscribe(observer) { + var q = [], previous = true; + + var subscription = + combineLatestSource( + this.source, + this.subject.distinctUntilChanged(), + function (data, shouldFire) { + return { data: data, shouldFire: shouldFire }; + }) + .subscribe( + function (results) { + if (results.shouldFire && previous) { + observer.onNext(results.data); + } + if (results.shouldFire && !previous) { + while (q.length > 0) { + observer.onNext(q.shift()); + } + previous = true; + } else if (!results.shouldFire && !previous) { + q.push(results.data); + } else if (!results.shouldFire && previous) { + previous = false; + } + + }, + function (err) { + // Empty buffer before sending error + while (q.length > 0) { + observer.onNext(q.shift()); + } + observer.onError(err); + }, + function () { + // Empty buffer before sending completion + while (q.length > 0) { + observer.onNext(q.shift()); + } + observer.onCompleted(); + } + ); + + this.subject.onNext(false); + + return subscription; + } + + function PausableBufferedObservable(source, subject) { + this.source = source; + this.subject = subject || new Subject(); + this.isPaused = true; + _super.call(this, subscribe); + } + + PausableBufferedObservable.prototype.pause = function () { + if (this.isPaused === true){ + return; + } + this.isPaused = true; + this.subject.onNext(false); + }; + + PausableBufferedObservable.prototype.resume = function () { + if (this.isPaused === false){ + return; + } + this.isPaused = false; + this.subject.onNext(true); + }; + + return PausableBufferedObservable; + + }(Observable)); + + /** + * Pauses the underlying observable sequence based upon the observable sequence which yields true/false, + * and yields the values that were buffered while paused. + * @example + * var pauser = new Rx.Subject(); + * var source = Rx.Observable.interval(100).pausableBuffered(pauser); + * @param {Observable} pauser The observable sequence used to pause the underlying sequence. + * @returns {Observable} The observable sequence which is paused based upon the pauser. + */ + observableProto.pausableBuffered = function (subject) { + return new PausableBufferedObservable(this, subject); + }; + + /** + * Attaches a controller to the observable sequence with the ability to queue. + * @example + * var source = Rx.Observable.interval(100).controlled(); + * source.request(3); // Reads 3 values + * @param {Observable} pauser The observable sequence used to pause the underlying sequence. + * @returns {Observable} The observable sequence which is paused based upon the pauser. + */ + observableProto.controlled = function (enableQueue) { + if (enableQueue == null) { enableQueue = true; } + return new ControlledObservable(this, enableQueue); + }; + var ControlledObservable = (function (_super) { + + inherits(ControlledObservable, _super); + + function subscribe (observer) { + return this.source.subscribe(observer); + } + + function ControlledObservable (source, enableQueue) { + _super.call(this, subscribe); + this.subject = new ControlledSubject(enableQueue); + this.source = source.multicast(this.subject).refCount(); + } + + ControlledObservable.prototype.request = function (numberOfItems) { + if (numberOfItems == null) { numberOfItems = -1; } + return this.subject.request(numberOfItems); + }; + + return ControlledObservable; + + }(Observable)); + + var ControlledSubject = Rx.ControlledSubject = (function (_super) { + + function subscribe (observer) { + return this.subject.subscribe(observer); + } + + inherits(ControlledSubject, _super); + + function ControlledSubject(enableQueue) { + if (enableQueue == null) { + enableQueue = true; + } + + _super.call(this, subscribe); + this.subject = new Subject(); + this.enableQueue = enableQueue; + this.queue = enableQueue ? [] : null; + this.requestedCount = 0; + this.requestedDisposable = disposableEmpty; + this.error = null; + this.hasFailed = false; + this.hasCompleted = false; + this.controlledDisposable = disposableEmpty; + } + + addProperties(ControlledSubject.prototype, Observer, { + onCompleted: function () { + checkDisposed.call(this); + this.hasCompleted = true; + + if (!this.enableQueue || this.queue.length === 0) { + this.subject.onCompleted(); + } + }, + onError: function (error) { + checkDisposed.call(this); + this.hasFailed = true; + this.error = error; + + if (!this.enableQueue || this.queue.length === 0) { + this.subject.onError(error); + } + }, + onNext: function (value) { + checkDisposed.call(this); + var hasRequested = false; + + if (this.requestedCount === 0) { + if (this.enableQueue) { + this.queue.push(value); + } + } else { + if (this.requestedCount !== -1) { + if (this.requestedCount-- === 0) { + this.disposeCurrentRequest(); + } + } + hasRequested = true; + } + + if (hasRequested) { + this.subject.onNext(value); + } + }, + _processRequest: function (numberOfItems) { + if (this.enableQueue) { + //console.log('queue length', this.queue.length); + + while (this.queue.length >= numberOfItems && numberOfItems > 0) { + //console.log('number of items', numberOfItems); + this.subject.onNext(this.queue.shift()); + numberOfItems--; + } + + if (this.queue.length !== 0) { + return { numberOfItems: numberOfItems, returnValue: true }; + } else { + return { numberOfItems: numberOfItems, returnValue: false }; + } + } + + if (this.hasFailed) { + this.subject.onError(this.error); + this.controlledDisposable.dispose(); + this.controlledDisposable = disposableEmpty; + } else if (this.hasCompleted) { + this.subject.onCompleted(); + this.controlledDisposable.dispose(); + this.controlledDisposable = disposableEmpty; + } + + return { numberOfItems: numberOfItems, returnValue: false }; + }, + request: function (number) { + checkDisposed.call(this); + this.disposeCurrentRequest(); + var self = this, + r = this._processRequest(number); + + number = r.numberOfItems; + if (!r.returnValue) { + this.requestedCount = number; + this.requestedDisposable = disposableCreate(function () { + self.requestedCount = 0; + }); + + return this.requestedDisposable + } else { + return disposableEmpty; + } + }, + disposeCurrentRequest: function () { + this.requestedDisposable.dispose(); + this.requestedDisposable = disposableEmpty; + }, + + dispose: function () { + this.isDisposed = true; + this.error = null; + this.subject.dispose(); + this.requestedDisposable.dispose(); + } + }); + + return ControlledSubject; + }(Observable)); + return Rx; +})); \ No newline at end of file diff --git a/ajax/libs/rxjs/2.2.28/rx.backpressure.min.js b/ajax/libs/rxjs/2.2.28/rx.backpressure.min.js new file mode 100644 index 000000000..6d908ea0c --- /dev/null +++ b/ajax/libs/rxjs/2.2.28/rx.backpressure.min.js @@ -0,0 +1 @@ +(function(t){var e={"boolean":!1,"function":!0,object:!0,number:!1,string:!1,undefined:!1},n=e[typeof window]&&window||this,r=e[typeof exports]&&exports&&!exports.nodeType&&exports,i=e[typeof module]&&module&&!module.nodeType&&module,o=(i&&i.exports===r&&r,e[typeof global]&&global);!o||o.global!==o&&o.window!==o||(n=o),"function"==typeof define&&define.amd?define(["rx","exports"],function(e,r){return n.Rx=t(n,r,e),n.Rx}):"object"==typeof module&&module&&module.exports===r?module.exports=t(n,module.exports,require("./rx")):n.Rx=t(n,{},n.Rx)}).call(this,function(t,e,n){function r(){if(this.isDisposed)throw Error(b)}function i(t,e,n){return new u(function(r){function i(t,e){h[e]=t;var i;if(s[e]=!0,u||(u=s.every(v))){try{i=n.apply(null,h)}catch(o){return r.onError(o),undefined}r.onNext(i)}else a&&r.onCompleted()}var o=2,s=[!1,!1],u=!1,a=!1,h=Array(o);return new c(t.subscribe(function(t){i(t,0)},r.onError.bind(r),function(){a=!0,r.onCompleted()}),e.subscribe(function(t){i(t,1)},r.onError.bind(r)))})}var o=n.Observable,s=o.prototype,u=n.AnonymousObservable,c=n.CompositeDisposable,a=n.Subject,h=n.Observer,l=n.Disposable.empty,f=n.Disposable.create,p=n.internals.inherits,d=n.internals.addProperties,v=(n.Scheduler.timeout,n.helpers.identity),b="Object has been disposed",m=function(t){function e(t){var e=this.source.publish(),n=e.subscribe(t),r=l,i=this.subject.distinctUntilChanged().subscribe(function(t){t?r=e.connect():(r.dispose(),r=l)});return new c(n,r,i)}function n(n,r){this.source=n,this.subject=r||new a,this.isPaused=!0,t.call(this,e)}return p(n,t),n.prototype.pause=function(){this.isPaused!==!0&&(this.isPaused=!0,this.subject.onNext(!1))},n.prototype.resume=function(){this.isPaused!==!1&&(this.isPaused=!1,this.subject.onNext(!0))},n}(o);s.pausable=function(t){return new m(this,t)};var y=function(t){function e(t){var e=[],n=!0,r=i(this.source,this.subject.distinctUntilChanged(),function(t,e){return{data:t,shouldFire:e}}).subscribe(function(r){if(r.shouldFire&&n&&t.onNext(r.data),r.shouldFire&&!n){for(;e.length>0;)t.onNext(e.shift());n=!0}else r.shouldFire||n?!r.shouldFire&&n&&(n=!1):e.push(r.data)},function(n){for(;e.length>0;)t.onNext(e.shift());t.onError(n)},function(){for(;e.length>0;)t.onNext(e.shift());t.onCompleted()});return this.subject.onNext(!1),r}function n(n,r){this.source=n,this.subject=r||new a,this.isPaused=!0,t.call(this,e)}return p(n,t),n.prototype.pause=function(){this.isPaused!==!0&&(this.isPaused=!0,this.subject.onNext(!1))},n.prototype.resume=function(){this.isPaused!==!1&&(this.isPaused=!1,this.subject.onNext(!0))},n}(o);s.pausableBuffered=function(t){return new y(this,t)},s.controlled=function(t){return null==t&&(t=!0),new w(this,t)};var w=function(t){function e(t){return this.source.subscribe(t)}function n(n,r){t.call(this,e),this.subject=new g(r),this.source=n.multicast(this.subject).refCount()}return p(n,t),n.prototype.request=function(t){return null==t&&(t=-1),this.subject.request(t)},n}(o),g=n.ControlledSubject=function(t){function e(t){return this.subject.subscribe(t)}function n(n){null==n&&(n=!0),t.call(this,e),this.subject=new a,this.enableQueue=n,this.queue=n?[]:null,this.requestedCount=0,this.requestedDisposable=l,this.error=null,this.hasFailed=!1,this.hasCompleted=!1,this.controlledDisposable=l}return p(n,t),d(n.prototype,h,{onCompleted:function(){r.call(this),this.hasCompleted=!0,this.enableQueue&&0!==this.queue.length||this.subject.onCompleted()},onError:function(t){r.call(this),this.hasFailed=!0,this.error=t,this.enableQueue&&0!==this.queue.length||this.subject.onError(t)},onNext:function(t){r.call(this);var e=!1;0===this.requestedCount?this.enableQueue&&this.queue.push(t):(-1!==this.requestedCount&&0===this.requestedCount--&&this.disposeCurrentRequest(),e=!0),e&&this.subject.onNext(t)},_processRequest:function(t){if(this.enableQueue){for(;this.queue.length>=t&&t>0;)this.subject.onNext(this.queue.shift()),t--;return 0!==this.queue.length?{numberOfItems:t,returnValue:!0}:{numberOfItems:t,returnValue:!1}}return this.hasFailed?(this.subject.onError(this.error),this.controlledDisposable.dispose(),this.controlledDisposable=l):this.hasCompleted&&(this.subject.onCompleted(),this.controlledDisposable.dispose(),this.controlledDisposable=l),{numberOfItems:t,returnValue:!1}},request:function(t){r.call(this),this.disposeCurrentRequest();var e=this,n=this._processRequest(t);return t=n.numberOfItems,n.returnValue?l:(this.requestedCount=t,this.requestedDisposable=f(function(){e.requestedCount=0}),this.requestedDisposable)},disposeCurrentRequest:function(){this.requestedDisposable.dispose(),this.requestedDisposable=l},dispose:function(){this.isDisposed=!0,this.error=null,this.subject.dispose(),this.requestedDisposable.dispose()}}),n}(o);return n}); \ No newline at end of file diff --git a/ajax/libs/rxjs/2.2.28/rx.binding.js b/ajax/libs/rxjs/2.2.28/rx.binding.js new file mode 100644 index 000000000..1d3f1adf6 --- /dev/null +++ b/ajax/libs/rxjs/2.2.28/rx.binding.js @@ -0,0 +1,561 @@ +// 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 (typeof define === 'function' && define.amd) { + define(['rx', 'exports'], function (Rx, exports) { + root.Rx = factory(root, exports, Rx); + return root.Rx; + }); + } 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, + inherits = Rx.internals.inherits, + addProperties = Rx.internals.addProperties; + + // Utilities + var objectDisposed = 'Object has been disposed'; + function checkDisposed() { + if (this.isDisposed) { + throw new Error(objectDisposed); + } + } + + /** + * 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.call(this); + if (!this.isStopped) { + var os = this.observers.slice(0); + this.isStopped = true; + for (var i = 0, len = os.length; i < len; i++) { + os[i].onCompleted(); + } + + this.observers = []; + } + }, + /** + * Notifies all subscribed observers about the exception. + * @param {Mixed} error The exception to send to all observers. + */ + onError: function (error) { + checkDisposed.call(this); + if (!this.isStopped) { + var os = this.observers.slice(0); + this.isStopped = true; + this.exception = error; + + for (var i = 0, len = os.length; i < len; i++) { + os[i].onError(error); + } + + this.observers = []; + } + }, + /** + * Notifies all subscribed observers about the arrival of the specified element in the sequence. + * @param {Mixed} value The value to send to all observers. + */ + onNext: function (value) { + checkDisposed.call(this); + if (!this.isStopped) { + this.value = value; + var os = this.observers.slice(0); + for (var i = 0, len = os.length; i < len; i++) { + os[i].onNext(value); + } + } + }, + /** + * Unsubscribe all observers and release resources. + */ + dispose: function () { + this.isDisposed = true; + this.observers = null; + this.value = null; + this.exception = null; + } + }); + + return BehaviorSubject; + }(Observable)); + + /** + * Represents an object that is both an observable sequence as well as an observer. + * Each notification is broadcasted to all subscribed and future observers, subject to buffer trimming policies. + */ + var ReplaySubject = Rx.ReplaySubject = (function (_super) { + + function RemovableDisposable (subject, observer) { + this.subject = subject; + this.observer = observer; + }; + + RemovableDisposable.prototype.dispose = function () { + this.observer.dispose(); + if (!this.subject.isDisposed) { + var idx = this.subject.observers.indexOf(this.observer); + this.subject.observers.splice(idx, 1); + } + }; + + function subscribe(observer) { + var so = new ScheduledObserver(this.scheduler, observer), + subscription = new RemovableDisposable(this, so); + checkDisposed.call(this); + this._trim(this.scheduler.now()); + this.observers.push(so); + + var n = this.q.length; + + for (var i = 0, len = this.q.length; i < len; i++) { + so.onNext(this.q[i].value); + } + + if (this.hasError) { + n++; + so.onError(this.error); + } else if (this.isStopped) { + n++; + so.onCompleted(); + } + + so.ensureActive(n); + return subscription; + } + + inherits(ReplaySubject, _super); + + /** + * Initializes a new instance of the ReplaySubject class with the specified buffer size, window size and scheduler. + * @param {Number} [bufferSize] Maximum element count of the replay buffer. + * @param {Number} [windowSize] Maximum time length of the replay buffer. + * @param {Scheduler} [scheduler] Scheduler the observers are invoked on. + */ + function ReplaySubject(bufferSize, windowSize, scheduler) { + this.bufferSize = bufferSize == null ? Number.MAX_VALUE : bufferSize; + this.windowSize = windowSize == null ? Number.MAX_VALUE : windowSize; + this.scheduler = scheduler || currentThreadScheduler; + this.q = []; + this.observers = []; + this.isStopped = false; + this.isDisposed = false; + this.hasError = false; + this.error = null; + _super.call(this, subscribe); + } + + addProperties(ReplaySubject.prototype, Observer, { + /** + * Indicates whether the subject has observers subscribed to it. + * @returns {Boolean} Indicates whether the subject has observers subscribed to it. + */ + hasObservers: function () { + return this.observers.length > 0; + }, + /* @private */ + _trim: function (now) { + while (this.q.length > this.bufferSize) { + this.q.shift(); + } + while (this.q.length > 0 && (now - this.q[0].interval) > this.windowSize) { + this.q.shift(); + } + }, + /** + * Notifies all subscribed observers about the arrival of the specified element in the sequence. + * @param {Mixed} value The value to send to all observers. + */ + onNext: function (value) { + var observer; + checkDisposed.call(this); + if (!this.isStopped) { + var now = this.scheduler.now(); + this.q.push({ interval: now, value: value }); + this._trim(now); + + var o = this.observers.slice(0); + for (var i = 0, len = o.length; i < len; i++) { + observer = o[i]; + observer.onNext(value); + observer.ensureActive(); + } + } + }, + /** + * Notifies all subscribed observers about the exception. + * @param {Mixed} error The exception to send to all observers. + */ + onError: function (error) { + var observer; + checkDisposed.call(this); + if (!this.isStopped) { + this.isStopped = true; + this.error = error; + this.hasError = true; + var now = this.scheduler.now(); + this._trim(now); + var o = this.observers.slice(0); + for (var i = 0, len = o.length; i < len; i++) { + observer = o[i]; + observer.onError(error); + observer.ensureActive(); + } + this.observers = []; + } + }, + /** + * Notifies all subscribed observers about the end of the sequence. + */ + onCompleted: function () { + var observer; + checkDisposed.call(this); + if (!this.isStopped) { + this.isStopped = true; + var now = this.scheduler.now(); + this._trim(now); + var o = this.observers.slice(0); + for (var i = 0, len = o.length; i < len; i++) { + observer = o[i]; + observer.onCompleted(); + observer.ensureActive(); + } + this.observers = []; + } + }, + /** + * Unsubscribe all observers and release resources. + */ + dispose: function () { + this.isDisposed = true; + this.observers = null; + } + }); + + return ReplaySubject; + }(Observable)); + + /** @private */ + var ConnectableObservable = Rx.ConnectableObservable = (function (_super) { + inherits(ConnectableObservable, _super); + + /** + * @constructor + * @private + */ + function ConnectableObservable(source, subject) { + var state = { + subject: subject, + source: source.asObservable(), + hasSubscription: false, + subscription: null + }; + + this.connect = function () { + if (!state.hasSubscription) { + state.hasSubscription = true; + state.subscription = new CompositeDisposable(state.source.subscribe(state.subject), disposableCreate(function () { + state.hasSubscription = false; + })); + } + return state.subscription; + }; + + function subscribe(observer) { + return state.subject.subscribe(observer); + } + + _super.call(this, subscribe); + } + + /** + * @private + * @memberOf ConnectableObservable + */ + ConnectableObservable.prototype.connect = function () { return this.connect(); }; + + /** + * @private + * @memberOf ConnectableObservable + */ + ConnectableObservable.prototype.refCount = function () { + var connectableSubscription = null, count = 0, source = this; + return new AnonymousObservable(function (observer) { + var shouldConnect, subscription; + count++; + shouldConnect = count === 1; + subscription = source.subscribe(observer); + if (shouldConnect) { + connectableSubscription = source.connect(); + } + return disposableCreate(function () { + subscription.dispose(); + count--; + if (count === 0) { + connectableSubscription.dispose(); + } + }); + }); + }; + + return ConnectableObservable; + }(Observable)); + + return Rx; +})); \ No newline at end of file diff --git a/ajax/libs/rxjs/2.2.28/rx.binding.min.js b/ajax/libs/rxjs/2.2.28/rx.binding.min.js new file mode 100644 index 000000000..5e98bb463 --- /dev/null +++ b/ajax/libs/rxjs/2.2.28/rx.binding.min.js @@ -0,0 +1 @@ +(function(t){var e={"boolean":!1,"function":!0,object:!0,number:!1,string:!1,undefined:!1},n=e[typeof window]&&window||this,r=e[typeof exports]&&exports&&!exports.nodeType&&exports,i=e[typeof module]&&module&&!module.nodeType&&module,o=(i&&i.exports===r&&r,e[typeof global]&&global);!o||o.global!==o&&o.window!==o||(n=o),"function"==typeof define&&define.amd?define(["rx","exports"],function(e,r){return n.Rx=t(n,r,e),n.Rx}):"object"==typeof module&&module&&module.exports===r?module.exports=t(n,module.exports,require("./rx")):n.Rx=t(n,{},n.Rx)}).call(this,function(t,e,n){function r(){if(this.isDisposed)throw Error(m)}var i=n.Observable,o=i.prototype,s=n.AnonymousObservable,u=n.Subject,c=n.AsyncSubject,a=n.Observer,h=n.internals.ScheduledObserver,l=n.Disposable.create,f=n.Disposable.empty,p=n.CompositeDisposable,d=n.Scheduler.currentThread,b=n.internals.inherits,v=n.internals.addProperties,m="Object has been disposed";o.multicast=function(t,e){var n=this;return"function"==typeof t?new s(function(r){var i=n.multicast(t());return new p(e(i).subscribe(r),i.connect())}):new E(n,t)},o.publish=function(t){return t?this.multicast(function(){return new u},t):this.multicast(new u)},o.share=function(){return this.publish(null).refCount()},o.publishLast=function(t){return t?this.multicast(function(){return new c},t):this.multicast(new c)},o.publishValue=function(t,e){return 2===arguments.length?this.multicast(function(){return new w(e)},t):this.multicast(new w(t))},o.shareValue=function(t){return this.publishValue(t).refCount()},o.replay=function(t,e,n,r){return t?this.multicast(function(){return new g(e,n,r)},t):this.multicast(new g(e,n,r))},o.shareReplay=function(t,e,n){return this.replay(null,t,e,n).refCount()};var y=function(t,e){this.subject=t,this.observer=e};y.prototype.dispose=function(){if(!this.subject.isDisposed&&null!==this.observer){var t=this.subject.observers.indexOf(this.observer);this.subject.observers.splice(t,1),this.observer=null}};var w=n.BehaviorSubject=function(t){function e(t){if(r.call(this),!this.isStopped)return this.observers.push(t),t.onNext(this.value),new y(this,t);var e=this.exception;return e?t.onError(e):t.onCompleted(),f}function n(n){t.call(this,e),this.value=n,this.observers=[],this.isDisposed=!1,this.isStopped=!1,this.exception=null}return b(n,t),v(n.prototype,a,{hasObservers:function(){return this.observers.length>0},onCompleted:function(){if(r.call(this),!this.isStopped){var t=this.observers.slice(0);this.isStopped=!0;for(var e=0,n=t.length;n>e;e++)t[e].onCompleted();this.observers=[]}},onError:function(t){if(r.call(this),!this.isStopped){var e=this.observers.slice(0);this.isStopped=!0,this.exception=t;for(var n=0,i=e.length;i>n;n++)e[n].onError(t);this.observers=[]}},onNext:function(t){if(r.call(this),!this.isStopped){this.value=t;for(var e=this.observers.slice(0),n=0,i=e.length;i>n;n++)e[n].onNext(t)}},dispose:function(){this.isDisposed=!0,this.observers=null,this.value=null,this.exception=null}}),n}(i),g=n.ReplaySubject=function(t){function e(t,e){this.subject=t,this.observer=e}function n(t){var n=new h(this.scheduler,t),i=new e(this,n);r.call(this),this._trim(this.scheduler.now()),this.observers.push(n);for(var o=this.q.length,s=0,u=this.q.length;u>s;s++)n.onNext(this.q[s].value);return this.hasError?(o++,n.onError(this.error)):this.isStopped&&(o++,n.onCompleted()),n.ensureActive(o),i}function i(e,r,i){this.bufferSize=null==e?Number.MAX_VALUE:e,this.windowSize=null==r?Number.MAX_VALUE:r,this.scheduler=i||d,this.q=[],this.observers=[],this.isStopped=!1,this.isDisposed=!1,this.hasError=!1,this.error=null,t.call(this,n)}return e.prototype.dispose=function(){if(this.observer.dispose(),!this.subject.isDisposed){var t=this.subject.observers.indexOf(this.observer);this.subject.observers.splice(t,1)}},b(i,t),v(i.prototype,a,{hasObservers:function(){return this.observers.length>0},_trim:function(t){for(;this.q.length>this.bufferSize;)this.q.shift();for(;this.q.length>0&&t-this.q[0].interval>this.windowSize;)this.q.shift()},onNext:function(t){var e;if(r.call(this),!this.isStopped){var n=this.scheduler.now();this.q.push({interval:n,value:t}),this._trim(n);for(var i=this.observers.slice(0),o=0,s=i.length;s>o;o++)e=i[o],e.onNext(t),e.ensureActive()}},onError:function(t){var e;if(r.call(this),!this.isStopped){this.isStopped=!0,this.error=t,this.hasError=!0;var n=this.scheduler.now();this._trim(n);for(var i=this.observers.slice(0),o=0,s=i.length;s>o;o++)e=i[o],e.onError(t),e.ensureActive();this.observers=[]}},onCompleted:function(){var t;if(r.call(this),!this.isStopped){this.isStopped=!0;var e=this.scheduler.now();this._trim(e);for(var n=this.observers.slice(0),i=0,o=n.length;o>i;i++)t=n[i],t.onCompleted(),t.ensureActive();this.observers=[]}},dispose:function(){this.isDisposed=!0,this.observers=null}}),i}(i),E=n.ConnectableObservable=function(t){function e(e,n){function r(t){return i.subject.subscribe(t)}var i={subject:n,source:e.asObservable(),hasSubscription:!1,subscription:null};this.connect=function(){return i.hasSubscription||(i.hasSubscription=!0,i.subscription=new p(i.source.subscribe(i.subject),l(function(){i.hasSubscription=!1}))),i.subscription},t.call(this,r)}return b(e,t),e.prototype.connect=function(){return this.connect()},e.prototype.refCount=function(){var t=null,e=0,n=this;return new s(function(r){var i,o;return e++,i=1===e,o=n.subscribe(r),i&&(t=n.connect()),l(function(){o.dispose(),e--,0===e&&t.dispose()})})},e}(i);return n}); \ No newline at end of file diff --git a/ajax/libs/rxjs/2.2.28/rx.coincidence.js b/ajax/libs/rxjs/2.2.28/rx.coincidence.js new file mode 100644 index 000000000..3eee13a02 --- /dev/null +++ b/ajax/libs/rxjs/2.2.28/rx.coincidence.js @@ -0,0 +1,733 @@ +// 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 (typeof define === 'function' && define.amd) { + define(['rx', 'exports'], function (Rx, exports) { + root.Rx = factory(root, exports, Rx); + return root.Rx; + }); + } 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, + AnonymousObservable = Rx.AnonymousObservable, + observerCreate = Rx.Observer.create, + addRef = Rx.internals.addRef, + defaultComparer = Rx.internals.isEqual, + noop = Rx.helpers.noop; + + // Real Dictionary + 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]; + var noSuchkey = "no such key"; + var 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 obj.getTime(); + } + + if (obj.getHashCode) { + return obj.getHashCode(); + } + + var id = 17 * uniqueIdCounter++; + obj.getHashCode = function () { return id; }; + return id; + }; + } ()); + + function newEntry() { + return { key: null, value: null, next: 0, hashCode: 0 }; + } + + // Dictionary implementation + + var Dictionary = function (capacity, comparer) { + if (capacity < 0) { + throw new Error('out of range') + } + if (capacity > 0) { + this._initialize(capacity); + } + + this.comparer = comparer || defaultComparer; + this.freeCount = 0; + this.size = 0; + this.freeList = -1; + }; + + Dictionary.prototype._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; + }; + Dictionary.prototype.count = function () { + return this.size; + }; + Dictionary.prototype.add = function (key, value) { + return this._insert(key, value, true); + }; + Dictionary.prototype._insert = function (key, value, add) { + if (!this.buckets) { + this._initialize(0); + } + var index3; + var num = getHashCode(key) & 2147483647; + var 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; + }; + + Dictionary.prototype._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; + }; + + Dictionary.prototype.remove = function (key) { + if (this.buckets) { + var num = getHashCode(key) & 2147483647; + var index1 = num % this.buckets.length; + var 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; + }; + + Dictionary.prototype.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; + }; + + Dictionary.prototype._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; + }; + + Dictionary.prototype.count = function () { + return this.size - this.freeCount; + }; + + Dictionary.prototype.tryGetValue = function (key) { + var entry = this._findEntry(key); + if (entry >= 0) { + return this.entries[entry].value; + } + return undefined; + }; + + Dictionary.prototype.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; + }; + + Dictionary.prototype.get = function (key) { + var entry = this._findEntry(key); + if (entry >= 0) { + return this.entries[entry].value; + } + throw new Error(noSuchkey); + }; + + Dictionary.prototype.set = function (key, value) { + this._insert(key, value, false); + }; + + Dictionary.prototype.containskey = function (key) { + return this._findEntry(key) >= 0; + }; + + /** + * 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(), + leftDone = false, + leftId = 0, + leftMap = new Dictionary(), + rightDone = false, + rightId = 0, + rightMap = new Dictionary(); + group.add(left.subscribe(function (value) { + var duration, + expire, + id = leftId++, + md = new SingleAssignmentDisposable(), + result, + values; + leftMap.add(id, value); + group.add(md); + expire = function () { + if (leftMap.remove(id) && leftMap.count() === 0 && leftDone) { + observer.onCompleted(); + } + return group.remove(md); + }; + try { + duration = leftDurationSelector(value); + } catch (e) { + observer.onError(e); + return; + } + md.setDisposable(duration.take(1).subscribe(noop, observer.onError.bind(observer), function () { expire(); })); + values = rightMap.getValues(); + for (var i = 0; i < values.length; i++) { + try { + result = resultSelector(value, values[i]); + } catch (exception) { + observer.onError(exception); + return; + } + observer.onNext(result); + } + }, observer.onError.bind(observer), function () { + leftDone = true; + if (rightDone || leftMap.count() === 0) { + observer.onCompleted(); + } + })); + group.add(right.subscribe(function (value) { + var duration, + expire, + id = rightId++, + md = new SingleAssignmentDisposable(), + result, + values; + rightMap.add(id, value); + group.add(md); + expire = function () { + if (rightMap.remove(id) && rightMap.count() === 0 && rightDone) { + observer.onCompleted(); + } + return group.remove(md); + }; + try { + duration = rightDurationSelector(value); + } catch (exception) { + observer.onError(exception); + return; + } + md.setDisposable(duration.take(1).subscribe(noop, observer.onError.bind(observer), function () { expire(); })); + values = leftMap.getValues(); + for (var i = 0; i < values.length; i++) { + try { + result = resultSelector(values[i], value); + } catch (exception) { + observer.onError(exception); + return; + } + observer.onNext(result); + } + }, observer.onError.bind(observer), function () { + rightDone = true; + if (leftDone || rightMap.count() === 0) { + observer.onCompleted(); + } + })); + return group; + }); + }; + + /** + * Correlates the elements of two sequences based on overlapping durations, and groups the results. + * + * @param {Observable} right The right observable sequence to join elements for. + * @param {Function} leftDurationSelector A function to select the duration (expressed as an observable sequence) of each element of the left observable sequence, used to determine overlap. + * @param {Function} rightDurationSelector A function to select the duration (expressed as an observable sequence) of each element of the right observable sequence, used to determine overlap. + * @param {Function} resultSelector A function invoked to compute a result element for any element of the left sequence with overlapping elements from the right observable sequence. The first parameter passed to the function is an element of the left sequence. The second parameter passed to the function is an observable sequence with elements from the right sequence that overlap with the left sequence's element. + * @returns {Observable} An observable sequence that contains result elements computed from source elements that have an overlapping duration. + */ + observableProto.groupJoin = function (right, leftDurationSelector, rightDurationSelector, resultSelector) { + var left = this; + return new AnonymousObservable(function (observer) { + var nothing = function () {}; + var group = new CompositeDisposable(); + var r = new RefCountDisposable(group); + var leftMap = new Dictionary(); + var rightMap = new Dictionary(); + var leftID = 0; + var rightID = 0; + + group.add(left.subscribe( + function (value) { + var s = new Subject(); + var id = leftID++; + leftMap.add(id, s); + var i, len, leftValues, rightValues; + + var result; + try { + result = resultSelector(value, addRef(s, r)); + } catch (e) { + leftValues = leftMap.getValues(); + for (i = 0, len = leftValues.length; i < len; i++) { + leftValues[i].onError(e); + } + observer.onError(e); + return; + } + observer.onNext(result); + + rightValues = rightMap.getValues(); + for (i = 0, len = rightValues.length; i < len; i++) { + s.onNext(rightValues[i]); + } + + var md = new SingleAssignmentDisposable(); + group.add(md); + + var expire = function () { + if (leftMap.remove(id)) { + s.onCompleted(); + } + + group.remove(md); + }; + + var duration; + try { + duration = leftDurationSelector(value); + } catch (e) { + leftValues = leftMap.getValues(); + for (i = 0, len = leftMap.length; i < len; i++) { + leftValues[i].onError(e); + } + observer.onError(e); + return; + } + + md.setDisposable(duration.take(1).subscribe( + nothing, + function (e) { + leftValues = leftMap.getValues(); + for (i = 0, len = leftValues.length; i < len; i++) { + leftValues[i].onError(e); + } + observer.onError(e); + }, + expire) + ); + }, + function (e) { + var leftValues = leftMap.getValues(); + for (var i = 0, len = leftValues.length; i < len; i++) { + leftValues[i].onError(e); + } + observer.onError(e); + }, + observer.onCompleted.bind(observer))); + + group.add(right.subscribe( + function (value) { + var leftValues, i, len; + 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) { + leftValues = leftMap.getValues(); + for (i = 0, len = leftMap.length; i < len; i++) { + leftValues[i].onError(e); + } + observer.onError(e); + return; + } + md.setDisposable(duration.take(1).subscribe( + nothing, + function (e) { + leftValues = leftMap.getValues(); + for (i = 0, len = leftMap.length; i < len; i++) { + leftValues[i].onError(e); + } + observer.onError(e); + }, + expire) + ); + + leftValues = leftMap.getValues(); + for (i = 0, len = leftValues.length; i < len; i++) { + leftValues[i].onNext(value); + } + }, + function (e) { + var leftValues = leftMap.getValues(); + for (var i = 0, len = leftValues.length; i < len; i++) { + leftValues[i].onError(e); + } + observer.onError(e); + })); + + return r; + }); + }; + + /** + * Projects each element of an observable sequence into zero or more buffers. + * + * @param {Mixed} bufferOpeningsOrClosingSelector Observable sequence whose elements denote the creation of new windows, or, a function invoked to define the boundaries of the produced windows (a new window is started when the previous one is closed, resulting in non-overlapping windows). + * @param {Function} [bufferClosingSelector] A function invoked to define the closing of each produced window. If a closing selector function is specified for the first parameter, this parameter is ignored. + * @returns {Observable} An observable sequence of windows. + */ + observableProto.buffer = function (bufferOpeningsOrClosingSelector, bufferClosingSelector) { + return this.window.apply(this, arguments).selectMany(function (x) { return x.toArray(); }); + }; + + /** + * Projects each element of an observable sequence into zero or more windows. + * + * @param {Mixed} windowOpeningsOrClosingSelector Observable sequence whose elements denote the creation of new windows, or, a function invoked to define the boundaries of the produced windows (a new window is started when the previous one is closed, resulting in non-overlapping windows). + * @param {Function} [windowClosingSelector] A function invoked to define the closing of each produced window. If a closing selector function is specified for the first parameter, this parameter is ignored. + * @returns {Observable} An observable sequence of windows. + */ + observableProto.window = function (windowOpeningsOrClosingSelector, windowClosingSelector) { + if (arguments.length === 1 && typeof arguments[0] !== 'function') { + return observableWindowWithBounaries.call(this, windowOpeningsOrClosingSelector); + } + return typeof windowOpeningsOrClosingSelector === 'function' ? + observableWindowWithClosingSelector.call(this, windowOpeningsOrClosingSelector) : + observableWindowWithOpenings.call(this, windowOpeningsOrClosingSelector, windowClosingSelector); + }; + + function observableWindowWithOpenings(windowOpenings, windowClosingSelector) { + return windowOpenings.groupJoin(this, windowClosingSelector, function () { + return observableEmpty(); + }, function (_, window) { + return window; + }); + } + + function observableWindowWithBounaries(windowBoundaries) { + var source = this; + return new AnonymousObservable(function (observer) { + var window = new Subject(), + d = new CompositeDisposable(), + r = new RefCountDisposable(d); + + observer.onNext(addRef(window, r)); + + d.add(source.subscribe(function (x) { + window.onNext(x); + }, function (err) { + window.onError(err); + observer.onError(err); + }, function () { + window.onCompleted(); + observer.onCompleted(); + })); + + d.add(windowBoundaries.subscribe(function (w) { + window.onCompleted(); + window = new Subject(); + observer.onNext(addRef(window, r)); + }, function (err) { + window.onError(err); + observer.onError(err); + }, function () { + window.onCompleted(); + observer.onCompleted(); + })); + + return r; + }); + } + + function observableWindowWithClosingSelector(windowClosingSelector) { + var source = this; + return new AnonymousObservable(function (observer) { + var createWindowClose, + m = new SerialDisposable(), + d = new CompositeDisposable(m), + r = new RefCountDisposable(d), + window = new Subject(); + observer.onNext(addRef(window, r)); + d.add(source.subscribe(function (x) { + window.onNext(x); + }, function (ex) { + window.onError(ex); + observer.onError(ex); + }, function () { + window.onCompleted(); + observer.onCompleted(); + })); + createWindowClose = function () { + var m1, windowClose; + try { + windowClose = windowClosingSelector(); + } catch (exception) { + observer.onError(exception); + return; + } + m1 = new SingleAssignmentDisposable(); + m.setDisposable(m1); + m1.setDisposable(windowClose.take(1).subscribe(noop, function (ex) { + window.onError(ex); + observer.onError(ex); + }, function () { + window.onCompleted(); + window = new Subject(); + observer.onNext(addRef(window, r)); + createWindowClose(); + })); + }; + createWindowClose(); + return r; + }); + } + + /** + * Returns a new observable that triggers on the second and subsequent triggerings of the input observable. + * The Nth triggering of the input observable passes the arguments from the N-1th and Nth triggering as a pair. + * The argument passed to the N-1th triggering is held in hidden internal state until the Nth triggering occurs. + * @returns {Observable} An observable that triggers on successive pairs of observations from the input observable as an array. + */ + observableProto.pairwise = function () { + var source = this; + return new AnonymousObservable(function (observer) { + var previous, hasPrevious = false; + return source.subscribe( + function (x) { + if (hasPrevious) { + observer.onNext([previous, x]); + } else { + hasPrevious = true; + } + previous = x; + }, + observer.onError.bind(observer), + observer.onCompleted.bind(observer)); + }); + }; + /** + * Returns two observables which partition the observations of the source by the given function. + * The first will trigger observations for those values for which the predicate returns true. + * The second will trigger observations for those values where the predicate returns false. + * The predicate is executed once for each subscribed observer. + * Both also propagate all error observations arising from the source and each completes + * when the source completes. + * @param {Function} predicate + * The function to determine which output Observable will trigger a particular observation. + * @returns {Array} + * An array of observables. The first triggers when the predicate returns true, + * and the second triggers when the predicate returns false. + */ + observableProto.partition = function(predicate, thisArg) { + var published = this.publish().refCount(); + return [ + published.filter(predicate, thisArg), + published.filter(function (x, i, o) { return !predicate.call(thisArg, x, i, o); }) + ]; + }; + + return Rx; +})); \ No newline at end of file diff --git a/ajax/libs/rxjs/2.2.28/rx.coincidence.min.js b/ajax/libs/rxjs/2.2.28/rx.coincidence.min.js new file mode 100644 index 000000000..326f0a5b5 --- /dev/null +++ b/ajax/libs/rxjs/2.2.28/rx.coincidence.min.js @@ -0,0 +1 @@ +(function(t){var e={"boolean":!1,"function":!0,object:!0,number:!1,string:!1,undefined:!1},n=e[typeof window]&&window||this,r=e[typeof exports]&&exports&&!exports.nodeType&&exports,i=e[typeof module]&&module&&!module.nodeType&&module,o=(i&&i.exports===r&&r,e[typeof global]&&global);!o||o.global!==o&&o.window!==o||(n=o),"function"==typeof define&&define.amd?define(["rx","exports"],function(e,r){return n.Rx=t(n,r,e),n.Rx}):"object"==typeof module&&module&&module.exports===r?module.exports=t(n,module.exports,require("./rx")):n.Rx=t(n,{},n.Rx)}).call(this,function(t,e,n,r){function i(t){if(false&t)return 2===t;for(var e=Math.sqrt(t),n=3;e>=n;){if(0===t%n)return!1;n+=2}return!0}function o(t){var e,n,r;for(e=0;D.length>e;++e)if(n=D[e],n>=t)return n;for(r=1|t;D[D.length-1]>r;){if(i(r))return r;r+=2}return t}function s(t){var e=757602046;if(!t.length)return e;for(var n=0,r=t.length;r>n;n++){var i=t.charCodeAt(n);e=(e<<5)-e+i,e&=e}return e}function u(t){var e=668265261;return t=61^t^t>>>16,t+=t<<3,t^=t>>>4,t*=e,t^=t>>>15}function c(){return{key:null,value:null,next:0,hashCode:0}}function a(t,e){return t.groupJoin(this,e,function(){return w()},function(t,e){return e})}function h(t){var e=this;return new g(function(n){var r=new m,i=new p,o=new d(i);return n.onNext(E(r,o)),i.add(e.subscribe(function(t){r.onNext(t)},function(t){r.onError(t),n.onError(t)},function(){r.onCompleted(),n.onCompleted()})),i.add(t.subscribe(function(){r.onCompleted(),r=new m,n.onNext(E(r,o))},function(t){r.onError(t),n.onError(t)},function(){r.onCompleted(),n.onCompleted()})),o})}function l(t){var e=this;return new g(function(n){var i,o=new v,s=new p(o),u=new d(s),c=new m;return n.onNext(E(c,u)),s.add(e.subscribe(function(t){c.onNext(t)},function(t){c.onError(t),n.onError(t)},function(){c.onCompleted(),n.onCompleted()})),i=function(){var e,s;try{s=t()}catch(a){return n.onError(a),r}e=new b,o.setDisposable(e),e.setDisposable(s.take(1).subscribe(C,function(t){c.onError(t),n.onError(t)},function(){c.onCompleted(),c=new m,n.onNext(E(c,u)),i()}))},i(),u})}var f=n.Observable,p=n.CompositeDisposable,d=n.RefCountDisposable,b=n.SingleAssignmentDisposable,v=n.SerialDisposable,m=n.Subject,y=f.prototype,w=f.empty,g=n.AnonymousObservable,E=(n.Observer.create,n.internals.addRef),x=n.internals.isEqual,C=n.helpers.noop,D=[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],S="no such key",N="duplicate key",A=function(){var t=0;return function(e){if(null==e)throw Error(S);if("string"==typeof e)return s(e);if("number"==typeof e)return u(e);if("boolean"==typeof e)return e===!0?1:0;if(e instanceof Date)return e.getTime();if(e.getHashCode)return e.getHashCode();var n=17*t++;return e.getHashCode=function(){return n},n}}(),_=function(t,e){if(0>t)throw Error("out of range");t>0&&this._initialize(t),this.comparer=e||x,this.freeCount=0,this.size=0,this.freeList=-1};return _.prototype._initialize=function(t){var e,n=o(t);for(this.buckets=Array(n),this.entries=Array(n),e=0;n>e;e++)this.buckets[e]=-1,this.entries[e]=c();this.freeList=-1},_.prototype.count=function(){return this.size},_.prototype.add=function(t,e){return this._insert(t,e,!0)},_.prototype._insert=function(t,e,n){this.buckets||this._initialize(0);for(var i,o=2147483647&A(t),s=o%this.buckets.length,u=this.buckets[s];u>=0;u=this.entries[u].next)if(this.entries[u].hashCode===o&&this.comparer(this.entries[u].key,t)){if(n)throw Error(N);return this.entries[u].value=e,r}this.freeCount>0?(i=this.freeList,this.freeList=this.entries[i].next,--this.freeCount):(this.size===this.entries.length&&(this._resize(),s=o%this.buckets.length),i=this.size,++this.size),this.entries[i].hashCode=o,this.entries[i].next=this.buckets[s],this.entries[i].key=t,this.entries[i].value=e,this.buckets[s]=i},_.prototype._resize=function(){var t=o(2*this.size),e=Array(t);for(r=0;e.length>r;++r)e[r]=-1;var n=Array(t);for(r=0;this.size>r;++r)n[r]=this.entries[r];for(var r=this.size;t>r;++r)n[r]=c();for(var i=0;this.size>i;++i){var s=n[i].hashCode%t;n[i].next=e[s],e[s]=i}this.buckets=e,this.entries=n},_.prototype.remove=function(t){if(this.buckets)for(var e=2147483647&A(t),n=e%this.buckets.length,r=-1,i=this.buckets[n];i>=0;i=this.entries[i].next){if(this.entries[i].hashCode===e&&this.comparer(this.entries[i].key,t))return 0>r?this.buckets[n]=this.entries[i].next:this.entries[r].next=this.entries[i].next,this.entries[i].hashCode=-1,this.entries[i].next=this.freeList,this.entries[i].key=null,this.entries[i].value=null,this.freeList=i,++this.freeCount,!0;r=i}return!1},_.prototype.clear=function(){var t,e;if(!(0>=this.size)){for(t=0,e=this.buckets.length;e>t;++t)this.buckets[t]=-1;for(t=0;this.size>t;++t)this.entries[t]=c();this.freeList=-1,this.size=0}},_.prototype._findEntry=function(t){if(this.buckets)for(var e=2147483647&A(t),n=this.buckets[e%this.buckets.length];n>=0;n=this.entries[n].next)if(this.entries[n].hashCode===e&&this.comparer(this.entries[n].key,t))return n;return-1},_.prototype.count=function(){return this.size-this.freeCount},_.prototype.tryGetValue=function(t){var e=this._findEntry(t);return e>=0?this.entries[e].value:r},_.prototype.getValues=function(){var t=0,e=[];if(this.entries)for(var n=0;this.size>n;n++)this.entries[n].hashCode>=0&&(e[t++]=this.entries[n].value);return e},_.prototype.get=function(t){var e=this._findEntry(t);if(e>=0)return this.entries[e].value;throw Error(S)},_.prototype.set=function(t,e){this._insert(t,e,!1)},_.prototype.containskey=function(t){return this._findEntry(t)>=0},y.join=function(t,e,n,i){var o=this;return new g(function(s){var u=new p,c=!1,a=0,h=new _,l=!1,f=0,d=new _;return u.add(o.subscribe(function(t){var n,o,l,f,p=a++,v=new b;h.add(p,t),u.add(v),o=function(){return h.remove(p)&&0===h.count()&&c&&s.onCompleted(),u.remove(v)};try{n=e(t)}catch(m){return s.onError(m),r}v.setDisposable(n.take(1).subscribe(C,s.onError.bind(s),function(){o()})),f=d.getValues();for(var y=0;f.length>y;y++){try{l=i(t,f[y])}catch(w){return s.onError(w),r}s.onNext(l)}},s.onError.bind(s),function(){c=!0,(l||0===h.count())&&s.onCompleted()})),u.add(t.subscribe(function(t){var e,o,c,a,p=f++,v=new b;d.add(p,t),u.add(v),o=function(){return d.remove(p)&&0===d.count()&&l&&s.onCompleted(),u.remove(v)};try{e=n(t)}catch(m){return s.onError(m),r}v.setDisposable(e.take(1).subscribe(C,s.onError.bind(s),function(){o()})),a=h.getValues();for(var y=0;a.length>y;y++){try{c=i(a[y],t)}catch(m){return s.onError(m),r}s.onNext(c)}},s.onError.bind(s),function(){l=!0,(c||0===d.count())&&s.onCompleted()})),u})},y.groupJoin=function(t,e,n,i){var o=this;return new g(function(s){var u=function(){},c=new p,a=new d(c),h=new _,l=new _,f=0,v=0;return c.add(o.subscribe(function(t){var n=new m,o=f++;h.add(o,n);var p,d,v,y,w;try{w=i(t,E(n,a))}catch(g){for(v=h.getValues(),p=0,d=v.length;d>p;p++)v[p].onError(g);return s.onError(g),r}for(s.onNext(w),y=l.getValues(),p=0,d=y.length;d>p;p++)n.onNext(y[p]);var x=new b;c.add(x);var C,D=function(){h.remove(o)&&n.onCompleted(),c.remove(x)};try{C=e(t)}catch(g){for(v=h.getValues(),p=0,d=h.length;d>p;p++)v[p].onError(g);return s.onError(g),r}x.setDisposable(C.take(1).subscribe(u,function(t){for(v=h.getValues(),p=0,d=v.length;d>p;p++)v[p].onError(t);s.onError(t)},D))},function(t){for(var e=h.getValues(),n=0,r=e.length;r>n;n++)e[n].onError(t);s.onError(t)},s.onCompleted.bind(s))),c.add(t.subscribe(function(t){var e,i,o,a=v++;l.add(a,t);var f=new b;c.add(f);var p,d=function(){l.remove(a),c.remove(f)};try{p=n(t)}catch(m){for(e=h.getValues(),i=0,o=h.length;o>i;i++)e[i].onError(m);return s.onError(m),r}for(f.setDisposable(p.take(1).subscribe(u,function(t){for(e=h.getValues(),i=0,o=h.length;o>i;i++)e[i].onError(t);s.onError(t)},d)),e=h.getValues(),i=0,o=e.length;o>i;i++)e[i].onNext(t)},function(t){for(var e=h.getValues(),n=0,r=e.length;r>n;n++)e[n].onError(t);s.onError(t)})),a})},y.buffer=function(){return this.window.apply(this,arguments).selectMany(function(t){return t.toArray()})},y.window=function(t,e){return 1===arguments.length&&"function"!=typeof arguments[0]?h.call(this,t):"function"==typeof t?l.call(this,t):a.call(this,t,e)},y.pairwise=function(){var t=this;return new g(function(e){var n,r=!1;return t.subscribe(function(t){r?e.onNext([n,t]):r=!0,n=t},e.onError.bind(e),e.onCompleted.bind(e))})},y.partition=function(t,e){var n=this.publish().refCount();return[n.filter(t,e),n.filter(function(n,r,i){return!t.call(e,n,r,i)})]},n}); \ No newline at end of file diff --git a/ajax/libs/rxjs/2.2.28/rx.compat.js b/ajax/libs/rxjs/2.2.28/rx.compat.js new file mode 100644 index 000000000..a84046d8a --- /dev/null +++ b/ajax/libs/rxjs/2.2.28/rx.compat.js @@ -0,0 +1,4758 @@ +// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. + +;(function (undefined) { + + var objectTypes = { + 'boolean': false, + 'function': true, + 'object': true, + 'number': false, + 'string': false, + 'undefined': false + }; + + var root = (objectTypes[typeof window] && window) || this, + freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports, + freeModule = objectTypes[typeof module] && module && !module.nodeType && module, + moduleExports = freeModule && freeModule.exports === freeExports && freeExports, + freeGlobal = objectTypes[typeof global] && global; + + if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal)) { + root = freeGlobal; + } + + var Rx = { + internals: {}, + config: { + Promise: root.Promise // Detect if promise exists + }, + helpers: { } + }; + + // Defaults + var noop = Rx.helpers.noop = function () { }, + identity = Rx.helpers.identity = function (x) { return x; }, + pluck = Rx.helpers.pluck = function (property) { return function (x) { return x[property]; }; }, + just = Rx.helpers.just = function (value) { return function () { return value; }; }, + defaultNow = Rx.helpers.defaultNow = (function () { return !!Date.now ? Date.now : function () { return +new Date; }; }()), + defaultComparer = Rx.helpers.defaultComparer = function (x, y) { return isEqual(x, y); }, + defaultSubComparer = Rx.helpers.defaultSubComparer = function (x, y) { return x > y ? 1 : (x < y ? -1 : 0); }, + defaultKeySerializer = Rx.helpers.defaultKeySerializer = function (x) { return x.toString(); }, + defaultError = Rx.helpers.defaultError = function (err) { throw err; }, + isPromise = Rx.helpers.isPromise = function (p) { return !!p && typeof p.then === 'function' && p.then !== Rx.Observable.prototype.then; }, + asArray = Rx.helpers.asArray = function () { return Array.prototype.slice.call(arguments); }, + not = Rx.helpers.not = function (a) { return !a; }; + + // Errors + var sequenceContainsNoElements = 'Sequence contains no elements.'; + var argumentOutOfRange = 'Argument out of range'; + var objectDisposed = 'Object has been disposed'; + function checkDisposed() { if (this.isDisposed) { throw new Error(objectDisposed); } } + + // Shim in iterator support + var $iterator$ = (typeof Symbol === 'object' && Symbol.iterator) || + '_es6shim_iterator_'; + // Firefox ships a partial implementation using the name @@iterator. + // https://bugzilla.mozilla.org/show_bug.cgi?id=907077#c14 + // So use that name if we detect it. + if (root.Set && typeof new root.Set()['@@iterator'] === 'function') { + $iterator$ = '@@iterator'; + } + var doneEnumerator = { done: true, value: undefined }; + + /** `Object#toString` result shortcuts */ + var argsClass = '[object Arguments]', + arrayClass = '[object Array]', + boolClass = '[object Boolean]', + dateClass = '[object Date]', + errorClass = '[object Error]', + funcClass = '[object Function]', + numberClass = '[object Number]', + objectClass = '[object Object]', + regexpClass = '[object RegExp]', + stringClass = '[object String]'; + + var toString = Object.prototype.toString, + hasOwnProperty = Object.prototype.hasOwnProperty, + supportsArgsClass = toString.call(arguments) == argsClass, // For less -1); + } + }); + } + } + stackA.pop(); + stackB.pop(); + + return result; + } + var slice = Array.prototype.slice; + function argsOrArray(args, idx) { + return args.length === 1 && Array.isArray(args[idx]) ? + args[idx] : + slice.call(args); + } + var hasProp = {}.hasOwnProperty; + + /** @private */ + var inherits = this.inherits = Rx.internals.inherits = function (child, parent) { + function __() { this.constructor = child; } + __.prototype = parent.prototype; + child.prototype = new __(); + }; + + /** @private */ + var addProperties = Rx.internals.addProperties = function (obj) { + var sources = slice.call(arguments, 1); + for (var i = 0, len = sources.length; i < len; i++) { + var source = sources[i]; + for (var prop in source) { + obj[prop] = source[prop]; + } + } + }; + + // Rx Utils + var addRef = Rx.internals.addRef = function (xs, r) { + return new AnonymousObservable(function (observer) { + return new CompositeDisposable(r.getDisposable(), xs.subscribe(observer)); + }); + }; + + // Collection polyfills + function arrayInitialize(count, factory) { + var a = new Array(count); + for (var i = 0; i < count; i++) { + a[i] = factory(); + } + return a; + } + + // Utilities + if (!Function.prototype.bind) { + Function.prototype.bind = function (that) { + var target = this, + args = slice.call(arguments, 1); + var bound = function () { + if (this instanceof bound) { + function F() { } + F.prototype = target.prototype; + var self = new F(); + var result = target.apply(self, args.concat(slice.call(arguments))); + if (Object(result) === result) { + return result; + } + return self; + } else { + return target.apply(that, args.concat(slice.call(arguments))); + } + }; + + return bound; + }; + } + + var boxedString = Object("a"), + splitString = boxedString[0] != "a" || !(0 in boxedString); + if (!Array.prototype.every) { + Array.prototype.every = function every(fun /*, thisp */) { + var object = Object(this), + self = splitString && {}.toString.call(this) == stringClass ? + this.split("") : + object, + length = self.length >>> 0, + thisp = arguments[1]; + + if ({}.toString.call(fun) != funcClass) { + throw new TypeError(fun + " is not a function"); + } + + for (var i = 0; i < length; i++) { + if (i in self && !fun.call(thisp, self[i], i, object)) { + return false; + } + } + return true; + }; + } + + if (!Array.prototype.map) { + Array.prototype.map = function map(fun /*, thisp*/) { + var object = Object(this), + self = splitString && {}.toString.call(this) == stringClass ? + this.split("") : + object, + length = self.length >>> 0, + result = Array(length), + thisp = arguments[1]; + + if ({}.toString.call(fun) != funcClass) { + throw new TypeError(fun + " is not a function"); + } + + for (var i = 0; i < length; i++) { + if (i in self) + result[i] = fun.call(thisp, self[i], i, object); + } + return result; + }; + } + + if (!Array.prototype.filter) { + Array.prototype.filter = function (predicate) { + var results = [], item, t = new Object(this); + for (var i = 0, len = t.length >>> 0; i < len; i++) { + item = t[i]; + if (i in t && predicate.call(arguments[1], item, i, t)) { + results.push(item); + } + } + return results; + }; + } + + if (!Array.isArray) { + Array.isArray = function (arg) { + return Object.prototype.toString.call(arg) == arrayClass; + }; + } + + if (!Array.prototype.indexOf) { + Array.prototype.indexOf = function indexOf(searchElement) { + var t = Object(this); + var len = t.length >>> 0; + if (len === 0) { + return -1; + } + var n = 0; + if (arguments.length > 1) { + n = Number(arguments[1]); + if (n !== n) { + n = 0; + } else if (n !== 0 && n != Infinity && n !== -Infinity) { + n = (n > 0 || -1) * Math.floor(Math.abs(n)); + } + } + if (n >= len) { + return -1; + } + var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0); + for (; k < len; k++) { + if (k in t && t[k] === searchElement) { + return k; + } + } + return -1; + }; + } + + // Collections + var IndexedItem = function (id, value) { + this.id = id; + this.value = value; + }; + + IndexedItem.prototype.compareTo = function (other) { + var c = this.value.compareTo(other.value); + if (c === 0) { + c = this.id - other.id; + } + return c; + }; + + // Priority Queue for Scheduling + var PriorityQueue = Rx.internals.PriorityQueue = function (capacity) { + this.items = new Array(capacity); + this.length = 0; + }; + + var priorityProto = PriorityQueue.prototype; + priorityProto.isHigherPriority = function (left, right) { + return this.items[left].compareTo(this.items[right]) < 0; + }; + + priorityProto.percolate = function (index) { + if (index >= this.length || index < 0) { + return; + } + var parent = index - 1 >> 1; + if (parent < 0 || parent === index) { + return; + } + if (this.isHigherPriority(index, parent)) { + var temp = this.items[index]; + this.items[index] = this.items[parent]; + this.items[parent] = temp; + this.percolate(parent); + } + }; + + priorityProto.heapify = function (index) { + if (index === undefined) { + index = 0; + } + if (index >= this.length || index < 0) { + return; + } + var left = 2 * index + 1, + right = 2 * index + 2, + first = index; + if (left < this.length && this.isHigherPriority(left, first)) { + first = left; + } + if (right < this.length && this.isHigherPriority(right, first)) { + first = right; + } + if (first !== index) { + var temp = this.items[index]; + this.items[index] = this.items[first]; + this.items[first] = temp; + this.heapify(first); + } + }; + + priorityProto.peek = function () { return this.items[0].value; }; + + priorityProto.removeAt = function (index) { + this.items[index] = this.items[--this.length]; + delete this.items[this.length]; + this.heapify(); + }; + + priorityProto.dequeue = function () { + var result = this.peek(); + this.removeAt(0); + return result; + }; + + priorityProto.enqueue = function (item) { + var index = this.length++; + this.items[index] = new IndexedItem(PriorityQueue.count++, item); + this.percolate(index); + }; + + priorityProto.remove = function (item) { + for (var i = 0; i < this.length; i++) { + if (this.items[i].value === item) { + this.removeAt(i); + return true; + } + } + return false; + }; + PriorityQueue.count = 0; + /** + * Represents a group of disposable resources that are disposed together. + * @constructor + */ + var CompositeDisposable = Rx.CompositeDisposable = function () { + this.disposables = argsOrArray(arguments, 0); + this.isDisposed = false; + this.length = this.disposables.length; + }; + + var CompositeDisposablePrototype = CompositeDisposable.prototype; + + /** + * Adds a disposable to the CompositeDisposable or disposes the disposable if the CompositeDisposable is disposed. + * @param {Mixed} item Disposable to add. + */ + CompositeDisposablePrototype.add = function (item) { + if (this.isDisposed) { + item.dispose(); + } else { + this.disposables.push(item); + this.length++; + } + }; + + /** + * Removes and disposes the first occurrence of a disposable from the CompositeDisposable. + * @param {Mixed} item Disposable to remove. + * @returns {Boolean} true if found; false otherwise. + */ + CompositeDisposablePrototype.remove = function (item) { + var shouldDispose = false; + if (!this.isDisposed) { + var idx = this.disposables.indexOf(item); + if (idx !== -1) { + shouldDispose = true; + this.disposables.splice(idx, 1); + this.length--; + item.dispose(); + } + + } + return shouldDispose; + }; + + /** + * Disposes all disposables in the group and removes them from the group. + */ + CompositeDisposablePrototype.dispose = function () { + if (!this.isDisposed) { + this.isDisposed = true; + var currentDisposables = this.disposables.slice(0); + this.disposables = []; + this.length = 0; + + for (var i = 0, len = currentDisposables.length; i < len; i++) { + currentDisposables[i].dispose(); + } + } + }; + + /** + * Removes and disposes all disposables from the CompositeDisposable, but does not dispose the CompositeDisposable. + */ + CompositeDisposablePrototype.clear = function () { + var currentDisposables = this.disposables.slice(0); + this.disposables = []; + this.length = 0; + for (var i = 0, len = currentDisposables.length; i < len; i++) { + currentDisposables[i].dispose(); + } + }; + + /** + * Determines whether the CompositeDisposable contains a specific disposable. + * @param {Mixed} item Disposable to search for. + * @returns {Boolean} true if the disposable was found; otherwise, false. + */ + CompositeDisposablePrototype.contains = function (item) { + return this.disposables.indexOf(item) !== -1; + }; + + /** + * Converts the existing CompositeDisposable to an array of disposables + * @returns {Array} An array of disposable objects. + */ + CompositeDisposablePrototype.toArray = function () { + return this.disposables.slice(0); + }; + + /** + * Provides a set of static methods for creating Disposables. + * + * @constructor + * @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once. + */ + var Disposable = Rx.Disposable = function (action) { + this.isDisposed = false; + this.action = action || noop; + }; + + /** Performs the task of cleaning up resources. */ + Disposable.prototype.dispose = function () { + if (!this.isDisposed) { + this.action(); + this.isDisposed = true; + } + }; + + /** + * Creates a disposable object that invokes the specified action when disposed. + * @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once. + * @return {Disposable} The disposable object that runs the given action upon disposal. + */ + var disposableCreate = Disposable.create = function (action) { return new Disposable(action); }; + + /** + * Gets the disposable that does nothing when disposed. + */ + var disposableEmpty = Disposable.empty = { dispose: noop }; + + var BooleanDisposable = (function () { + function BooleanDisposable (isSingle) { + this.isSingle = isSingle; + this.isDisposed = false; + this.current = null; + } + + var booleanDisposablePrototype = BooleanDisposable.prototype; + + /** + * Gets the underlying disposable. + * @return The underlying disposable. + */ + booleanDisposablePrototype.getDisposable = function () { + return this.current; + }; + + /** + * Sets the underlying disposable. + * @param {Disposable} value The new underlying disposable. + */ + booleanDisposablePrototype.setDisposable = function (value) { + if (this.current && this.isSingle) { + throw new Error('Disposable has already been assigned'); + } + + var shouldDispose = this.isDisposed, old; + if (!shouldDispose) { + old = this.current; + this.current = value; + } + if (old) { + old.dispose(); + } + if (shouldDispose && value) { + value.dispose(); + } + }; + + /** + * Disposes the underlying disposable as well as all future replacements. + */ + booleanDisposablePrototype.dispose = function () { + var old; + if (!this.isDisposed) { + this.isDisposed = true; + old = this.current; + this.current = null; + } + if (old) { + old.dispose(); + } + }; + + return BooleanDisposable; + }()); + + /** + * Represents a disposable resource which only allows a single assignment of its underlying disposable resource. + * If an underlying disposable resource has already been set, future attempts to set the underlying disposable resource will throw an Error. + */ + var SingleAssignmentDisposable = Rx.SingleAssignmentDisposable = (function (super_) { + inherits(SingleAssignmentDisposable, super_); + + function SingleAssignmentDisposable() { + super_.call(this, true); + } + + return SingleAssignmentDisposable; + }(BooleanDisposable)); + + /** + * Represents a disposable resource whose underlying disposable resource can be replaced by another disposable resource, causing automatic disposal of the previous underlying disposable resource. + */ + var SerialDisposable = Rx.SerialDisposable = (function (super_) { + inherits(SerialDisposable, super_); + + function SerialDisposable() { + super_.call(this, false); + } + + return SerialDisposable; + }(BooleanDisposable)); + + /** + * Represents a disposable resource that only disposes its underlying disposable resource when all dependent disposable objects have been disposed. + */ + var RefCountDisposable = Rx.RefCountDisposable = (function () { + + function InnerDisposable(disposable) { + this.disposable = disposable; + this.disposable.count++; + this.isInnerDisposed = false; + } + + InnerDisposable.prototype.dispose = function () { + if (!this.disposable.isDisposed) { + if (!this.isInnerDisposed) { + this.isInnerDisposed = true; + this.disposable.count--; + if (this.disposable.count === 0 && this.disposable.isPrimaryDisposed) { + this.disposable.isDisposed = true; + this.disposable.underlyingDisposable.dispose(); + } + } + } + }; + + /** + * Initializes a new instance of the RefCountDisposable with the specified disposable. + * @constructor + * @param {Disposable} disposable Underlying disposable. + */ + function RefCountDisposable(disposable) { + this.underlyingDisposable = disposable; + this.isDisposed = false; + this.isPrimaryDisposed = false; + this.count = 0; + } + + /** + * Disposes the underlying disposable only when all dependent disposables have been disposed + */ + RefCountDisposable.prototype.dispose = function () { + if (!this.isDisposed) { + if (!this.isPrimaryDisposed) { + this.isPrimaryDisposed = true; + if (this.count === 0) { + this.isDisposed = true; + this.underlyingDisposable.dispose(); + } + } + } + }; + + /** + * Returns a dependent disposable that when disposed decreases the refcount on the underlying disposable. + * @returns {Disposable} A dependent disposable contributing to the reference count that manages the underlying disposable's lifetime. + */ + RefCountDisposable.prototype.getDisposable = function () { + return this.isDisposed ? disposableEmpty : new InnerDisposable(this); + }; + + return RefCountDisposable; + })(); + + function ScheduledDisposable(scheduler, disposable) { + this.scheduler = scheduler; + this.disposable = disposable; + this.isDisposed = false; + } + + ScheduledDisposable.prototype.dispose = function () { + var parent = this; + this.scheduler.schedule(function () { + if (!parent.isDisposed) { + parent.isDisposed = true; + parent.disposable.dispose(); + } + }); + }; + + var ScheduledItem = Rx.internals.ScheduledItem = function (scheduler, state, action, dueTime, comparer) { + this.scheduler = scheduler; + this.state = state; + this.action = action; + this.dueTime = dueTime; + this.comparer = comparer || defaultSubComparer; + this.disposable = new SingleAssignmentDisposable(); + } + + ScheduledItem.prototype.invoke = function () { + this.disposable.setDisposable(this.invokeCore()); + }; + + ScheduledItem.prototype.compareTo = function (other) { + return this.comparer(this.dueTime, other.dueTime); + }; + + ScheduledItem.prototype.isCancelled = function () { + return this.disposable.isDisposed; + }; + + ScheduledItem.prototype.invokeCore = function () { + return this.action(this.scheduler, this.state); + }; + + /** Provides a set of static properties to access commonly used schedulers. */ + var Scheduler = Rx.Scheduler = (function () { + + /** + * @constructor + * @private + */ + function Scheduler(now, schedule, scheduleRelative, scheduleAbsolute) { + this.now = now; + this._schedule = schedule; + this._scheduleRelative = scheduleRelative; + this._scheduleAbsolute = scheduleAbsolute; + } + + function invokeRecImmediate(scheduler, pair) { + var state = pair.first, action = pair.second, group = new CompositeDisposable(), + recursiveAction = function (state1) { + action(state1, function (state2) { + var isAdded = false, isDone = false, + d = scheduler.scheduleWithState(state2, function (scheduler1, state3) { + if (isAdded) { + group.remove(d); + } else { + isDone = true; + } + recursiveAction(state3); + return disposableEmpty; + }); + if (!isDone) { + group.add(d); + isAdded = true; + } + }); + }; + recursiveAction(state); + return group; + } + + function invokeRecDate(scheduler, pair, method) { + var state = pair.first, action = pair.second, group = new CompositeDisposable(), + recursiveAction = function (state1) { + action(state1, function (state2, dueTime1) { + var isAdded = false, isDone = false, + d = scheduler[method].call(scheduler, state2, dueTime1, function (scheduler1, state3) { + if (isAdded) { + group.remove(d); + } else { + isDone = true; + } + recursiveAction(state3); + return disposableEmpty; + }); + if (!isDone) { + group.add(d); + isAdded = true; + } + }); + }; + recursiveAction(state); + return group; + } + + function invokeAction(scheduler, action) { + action(); + return disposableEmpty; + } + + var schedulerProto = Scheduler.prototype; + + /** + * Returns a scheduler that wraps the original scheduler, adding exception handling for scheduled actions. + * @param {Function} handler Handler that's run if an exception is caught. The exception will be rethrown if the handler returns false. + * @returns {Scheduler} Wrapper around the original scheduler, enforcing exception handling. + */ + schedulerProto.catchException = schedulerProto['catch'] = function (handler) { + return new CatchScheduler(this, handler); + }; + + /** + * Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation. + * @param {Number} period Period for running the work periodically. + * @param {Function} action Action to be executed. + * @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort). + */ + schedulerProto.schedulePeriodic = function (period, action) { + return this.schedulePeriodicWithState(null, period, function () { + action(); + }); + }; + + /** + * Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation. + * @param {Mixed} state Initial state passed to the action upon the first iteration. + * @param {Number} period Period for running the work periodically. + * @param {Function} action Action to be executed, potentially updating the state. + * @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort). + */ + schedulerProto.schedulePeriodicWithState = function (state, period, action) { + var s = state, id = setInterval(function () { + s = action(s); + }, period); + return disposableCreate(function () { + clearInterval(id); + }); + }; + + /** + * Schedules an action to be executed. + * @param {Function} action Action to execute. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.schedule = function (action) { + return this._schedule(action, invokeAction); + }; + + /** + * Schedules an action to be executed. + * @param state State passed to the action to be executed. + * @param {Function} action Action to be executed. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleWithState = function (state, action) { + return this._schedule(state, action); + }; + + /** + * Schedules an action to be executed after the specified relative due time. + * @param {Function} action Action to execute. + * @param {Number} dueTime Relative time after which to execute the action. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleWithRelative = function (dueTime, action) { + return this._scheduleRelative(action, dueTime, invokeAction); + }; + + /** + * Schedules an action to be executed after dueTime. + * @param state State passed to the action to be executed. + * @param {Function} action Action to be executed. + * @param {Number} dueTime Relative time after which to execute the action. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleWithRelativeAndState = function (state, dueTime, action) { + return this._scheduleRelative(state, dueTime, action); + }; + + /** + * Schedules an action to be executed at the specified absolute due time. + * @param {Function} action Action to execute. + * @param {Number} dueTime Absolute time at which to execute the action. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleWithAbsolute = function (dueTime, action) { + return this._scheduleAbsolute(action, dueTime, invokeAction); + }; + + /** + * Schedules an action to be executed at dueTime. + * @param {Mixed} state State passed to the action to be executed. + * @param {Function} action Action to be executed. + * @param {Number}dueTime Absolute time at which to execute the action. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleWithAbsoluteAndState = function (state, dueTime, action) { + return this._scheduleAbsolute(state, dueTime, action); + }; + + /** + * Schedules an action to be executed recursively. + * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleRecursive = function (action) { + return this.scheduleRecursiveWithState(action, function (_action, self) { + _action(function () { + self(_action); + }); + }); + }; + + /** + * Schedules an action to be executed recursively. + * @param {Mixed} state State passed to the action to be executed. + * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in recursive invocation state. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleRecursiveWithState = function (state, action) { + return this.scheduleWithState({ first: state, second: action }, function (s, p) { + return invokeRecImmediate(s, p); + }); + }; + + /** + * Schedules an action to be executed recursively after a specified relative due time. + * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified relative time. + * @param {Number}dueTime Relative time after which to execute the action for the first time. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleRecursiveWithRelative = function (dueTime, action) { + return this.scheduleRecursiveWithRelativeAndState(action, dueTime, function (_action, self) { + _action(function (dt) { + self(_action, dt); + }); + }); + }; + + /** + * Schedules an action to be executed recursively after a specified relative due time. + * @param {Mixed} state State passed to the action to be executed. + * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state. + * @param {Number}dueTime Relative time after which to execute the action for the first time. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleRecursiveWithRelativeAndState = function (state, dueTime, action) { + return this._scheduleRelative({ first: state, second: action }, dueTime, function (s, p) { + return invokeRecDate(s, p, 'scheduleWithRelativeAndState'); + }); + }; + + /** + * Schedules an action to be executed recursively at a specified absolute due time. + * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified absolute time. + * @param {Number}dueTime Absolute time at which to execute the action for the first time. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleRecursiveWithAbsolute = function (dueTime, action) { + return this.scheduleRecursiveWithAbsoluteAndState(action, dueTime, function (_action, self) { + _action(function (dt) { + self(_action, dt); + }); + }); + }; + + /** + * Schedules an action to be executed recursively at a specified absolute due time. + * @param {Mixed} state State passed to the action to be executed. + * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state. + * @param {Number}dueTime Absolute time at which to execute the action for the first time. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleRecursiveWithAbsoluteAndState = function (state, dueTime, action) { + return this._scheduleAbsolute({ first: state, second: action }, dueTime, function (s, p) { + return invokeRecDate(s, p, 'scheduleWithAbsoluteAndState'); + }); + }; + + /** Gets the current time according to the local machine's system clock. */ + Scheduler.now = defaultNow; + + /** + * Normalizes the specified TimeSpan value to a positive value. + * @param {Number} timeSpan The time span value to normalize. + * @returns {Number} The specified TimeSpan value if it is zero or positive; otherwise, 0 + */ + Scheduler.normalize = function (timeSpan) { + if (timeSpan < 0) { + timeSpan = 0; + } + return timeSpan; + }; + + return Scheduler; + }()); + + var normalizeTime = Scheduler.normalize; + + var SchedulePeriodicRecursive = Rx.internals.SchedulePeriodicRecursive = (function () { + function tick(command, recurse) { + recurse(0, this._period); + try { + this._state = this._action(this._state); + } catch (e) { + this._cancel.dispose(); + throw e; + } + } + + function SchedulePeriodicRecursive(scheduler, state, period, action) { + this._scheduler = scheduler; + this._state = state; + this._period = period; + this._action = action; + } + + SchedulePeriodicRecursive.prototype.start = function () { + var d = new SingleAssignmentDisposable(); + this._cancel = d; + d.setDisposable(this._scheduler.scheduleRecursiveWithRelativeAndState(0, this._period, tick.bind(this))); + + return d; + }; + + return SchedulePeriodicRecursive; + }()); + + /** + * Gets a scheduler that schedules work immediately on the current thread. + */ + var immediateScheduler = Scheduler.immediate = (function () { + + function scheduleNow(state, action) { return action(this, state); } + + function scheduleRelative(state, dueTime, action) { + var dt = normalizeTime(dt); + while (dt - this.now() > 0) { } + return action(this, state); + } + + function scheduleAbsolute(state, dueTime, action) { + return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); + } + + return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); + }()); + + /** + * Gets a scheduler that schedules work as soon as possible on the current thread. + */ + var currentThreadScheduler = Scheduler.currentThread = (function () { + var queue; + + function runTrampoline (q) { + var item; + while (q.length > 0) { + item = q.dequeue(); + if (!item.isCancelled()) { + // Note, do not schedule blocking work! + while (item.dueTime - Scheduler.now() > 0) { + } + if (!item.isCancelled()) { + item.invoke(); + } + } + } + } + + function scheduleNow(state, action) { + return this.scheduleWithRelativeAndState(state, 0, action); + } + + function scheduleRelative(state, dueTime, action) { + var dt = this.now() + Scheduler.normalize(dueTime), + si = new ScheduledItem(this, state, action, dt), + t; + if (!queue) { + queue = new PriorityQueue(4); + queue.enqueue(si); + try { + runTrampoline(queue); + } catch (e) { + throw e; + } finally { + queue = null; + } + } else { + queue.enqueue(si); + } + return si.disposable; + } + + function scheduleAbsolute(state, dueTime, action) { + return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); + } + + var currentScheduler = new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); + currentScheduler.scheduleRequired = function () { return queue === null; }; + currentScheduler.ensureTrampoline = function (action) { + if (queue === null) { + return this.schedule(action); + } else { + return action(); + } + }; + + return currentScheduler; + }()); + + + var scheduleMethod, clearMethod = noop; + (function () { + + var reNative = RegExp('^' + + String(toString) + .replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + .replace(/toString| for [^\]]+/g, '.*?') + '$' + ); + + var setImmediate = typeof (setImmediate = freeGlobal && moduleExports && freeGlobal.setImmediate) == 'function' && + !reNative.test(setImmediate) && setImmediate, + clearImmediate = typeof (clearImmediate = freeGlobal && moduleExports && freeGlobal.clearImmediate) == 'function' && + !reNative.test(clearImmediate) && clearImmediate; + + function postMessageSupported () { + // Ensure not in a worker + if (!root.postMessage || root.importScripts) { return false; } + var isAsync = false, + oldHandler = root.onmessage; + // Test for async + root.onmessage = function () { isAsync = true; }; + root.postMessage('','*'); + root.onmessage = oldHandler; + + return isAsync; + } + + // Use in order, nextTick, setImmediate, postMessage, MessageChannel, script readystatechanged, setTimeout + if (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]') { + scheduleMethod = process.nextTick; + } else if (typeof setImmediate === 'function') { + scheduleMethod = setImmediate; + clearMethod = clearImmediate; + } else if (postMessageSupported()) { + var MSG_PREFIX = 'ms.rx.schedule' + Math.random(), + tasks = {}, + taskId = 0; + + function onGlobalPostMessage(event) { + // Only if we're a match to avoid any other global events + if (typeof event.data === 'string' && event.data.substring(0, MSG_PREFIX.length) === MSG_PREFIX) { + var handleId = event.data.substring(MSG_PREFIX.length), + action = tasks[handleId]; + action(); + delete tasks[handleId]; + } + } + + if (root.addEventListener) { + root.addEventListener('message', onGlobalPostMessage, false); + } else { + root.attachEvent('onmessage', onGlobalPostMessage, false); + } + + scheduleMethod = function (action) { + var currentId = taskId++; + tasks[currentId] = action; + root.postMessage(MSG_PREFIX + currentId, '*'); + }; + } else if (!!root.MessageChannel) { + var channel = new root.MessageChannel(), + channelTasks = {}, + channelTaskId = 0; + + channel.port1.onmessage = function (event) { + var id = event.data, + action = channelTasks[id]; + action(); + delete channelTasks[id]; + }; + + scheduleMethod = function (action) { + var id = channelTaskId++; + channelTasks[id] = action; + channel.port2.postMessage(id); + }; + } else if ('document' in root && 'onreadystatechange' in root.document.createElement('script')) { + + scheduleMethod = function (action) { + var scriptElement = root.document.createElement('script'); + scriptElement.onreadystatechange = function () { + action(); + scriptElement.onreadystatechange = null; + scriptElement.parentNode.removeChild(scriptElement); + scriptElement = null; + }; + root.document.documentElement.appendChild(scriptElement); + }; + + } else { + scheduleMethod = function (action) { return setTimeout(action, 0); }; + clearMethod = clearTimeout; + } + }()); + + /** + * Gets a scheduler that schedules work via a timed callback based upon platform. + */ + var timeoutScheduler = Scheduler.timeout = (function () { + + function scheduleNow(state, action) { + var scheduler = this, + disposable = new SingleAssignmentDisposable(); + var id = scheduleMethod(function () { + if (!disposable.isDisposed) { + disposable.setDisposable(action(scheduler, state)); + } + }); + return new CompositeDisposable(disposable, disposableCreate(function () { + clearMethod(id); + })); + } + + function scheduleRelative(state, dueTime, action) { + var scheduler = this, + dt = Scheduler.normalize(dueTime); + if (dt === 0) { + return scheduler.scheduleWithState(state, action); + } + var disposable = new SingleAssignmentDisposable(); + var id = setTimeout(function () { + if (!disposable.isDisposed) { + disposable.setDisposable(action(scheduler, state)); + } + }, dt); + return new CompositeDisposable(disposable, disposableCreate(function () { + clearTimeout(id); + })); + } + + function scheduleAbsolute(state, dueTime, action) { + return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); + } + + return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); + })(); + + /** @private */ + var CatchScheduler = (function (_super) { + + function localNow() { + return this._scheduler.now(); + } + + function scheduleNow(state, action) { + return this._scheduler.scheduleWithState(state, this._wrap(action)); + } + + function scheduleRelative(state, dueTime, action) { + return this._scheduler.scheduleWithRelativeAndState(state, dueTime, this._wrap(action)); + } + + function scheduleAbsolute(state, dueTime, action) { + return this._scheduler.scheduleWithAbsoluteAndState(state, dueTime, this._wrap(action)); + } + + inherits(CatchScheduler, _super); + + /** @private */ + function CatchScheduler(scheduler, handler) { + this._scheduler = scheduler; + this._handler = handler; + this._recursiveOriginal = null; + this._recursiveWrapper = null; + _super.call(this, localNow, scheduleNow, scheduleRelative, scheduleAbsolute); + } + + /** @private */ + CatchScheduler.prototype._clone = function (scheduler) { + return new CatchScheduler(scheduler, this._handler); + }; + + /** @private */ + CatchScheduler.prototype._wrap = function (action) { + var parent = this; + return function (self, state) { + try { + return action(parent._getRecursiveWrapper(self), state); + } catch (e) { + if (!parent._handler(e)) { throw e; } + return disposableEmpty; + } + }; + }; + + /** @private */ + CatchScheduler.prototype._getRecursiveWrapper = function (scheduler) { + if (this._recursiveOriginal !== scheduler) { + this._recursiveOriginal = scheduler; + var wrapper = this._clone(scheduler); + wrapper._recursiveOriginal = scheduler; + wrapper._recursiveWrapper = wrapper; + this._recursiveWrapper = wrapper; + } + return this._recursiveWrapper; + }; + + /** @private */ + CatchScheduler.prototype.schedulePeriodicWithState = function (state, period, action) { + var self = this, failed = false, d = new SingleAssignmentDisposable(); + + d.setDisposable(this._scheduler.schedulePeriodicWithState(state, period, function (state1) { + if (failed) { return null; } + try { + return action(state1); + } catch (e) { + failed = true; + if (!self._handler(e)) { throw e; } + d.dispose(); + return null; + } + })); + + return d; + }; + + return CatchScheduler; + }(Scheduler)); + + /** + * Represents a notification to an observer. + */ + var Notification = Rx.Notification = (function () { + function Notification(kind, hasValue) { + this.hasValue = hasValue == null ? false : hasValue; + this.kind = kind; + } + + var NotificationPrototype = Notification.prototype; + + /** + * Invokes the delegate corresponding to the notification or the observer's method corresponding to the notification and returns the produced result. + * + * @memberOf Notification + * @param {Any} observerOrOnNext Delegate to invoke for an OnNext notification or Observer to invoke the notification on.. + * @param {Function} onError Delegate to invoke for an OnError notification. + * @param {Function} onCompleted Delegate to invoke for an OnCompleted notification. + * @returns {Any} Result produced by the observation. + */ + NotificationPrototype.accept = function (observerOrOnNext, onError, onCompleted) { + if (arguments.length === 1 && typeof observerOrOnNext === 'object') { + return this._acceptObservable(observerOrOnNext); + } + return this._accept(observerOrOnNext, onError, onCompleted); + }; + + /** + * Returns an observable sequence with a single notification. + * + * @memberOf Notification + * @param {Scheduler} [scheduler] Scheduler to send out the notification calls on. + * @returns {Observable} The observable sequence that surfaces the behavior of the notification upon subscription. + */ + NotificationPrototype.toObservable = function (scheduler) { + var notification = this; + scheduler || (scheduler = immediateScheduler); + return new AnonymousObservable(function (observer) { + return scheduler.schedule(function () { + notification._acceptObservable(observer); + if (notification.kind === 'N') { + observer.onCompleted(); + } + }); + }); + }; + + return Notification; + })(); + + /** + * Creates an object that represents an OnNext notification to an observer. + * @param {Any} value The value contained in the notification. + * @returns {Notification} The OnNext notification containing the value. + */ + var notificationCreateOnNext = Notification.createOnNext = (function () { + + function _accept (onNext) { + return onNext(this.value); + } + + function _acceptObservable(observer) { + return observer.onNext(this.value); + } + + function toString () { + return 'OnNext(' + this.value + ')'; + } + + return function (value) { + var notification = new Notification('N', true); + notification.value = value; + notification._accept = _accept; + notification._acceptObservable = _acceptObservable; + notification.toString = toString; + return notification; + }; + }()); + + /** + * Creates an object that represents an OnError notification to an observer. + * @param {Any} error The exception contained in the notification. + * @returns {Notification} The OnError notification containing the exception. + */ + var notificationCreateOnError = Notification.createOnError = (function () { + + function _accept (onNext, onError) { + return onError(this.exception); + } + + function _acceptObservable(observer) { + return observer.onError(this.exception); + } + + function toString () { + return 'OnError(' + this.exception + ')'; + } + + return function (exception) { + var notification = new Notification('E'); + notification.exception = exception; + notification._accept = _accept; + notification._acceptObservable = _acceptObservable; + notification.toString = toString; + return notification; + }; + }()); + + /** + * Creates an object that represents an OnCompleted notification to an observer. + * @returns {Notification} The OnCompleted notification. + */ + var notificationCreateOnCompleted = Notification.createOnCompleted = (function () { + + function _accept (onNext, onError, onCompleted) { + return onCompleted(); + } + + function _acceptObservable(observer) { + return observer.onCompleted(); + } + + function toString () { + return 'OnCompleted()'; + } + + return function () { + var notification = new Notification('C'); + notification._accept = _accept; + notification._acceptObservable = _acceptObservable; + notification.toString = toString; + return notification; + }; + }()); + + var Enumerator = Rx.internals.Enumerator = function (next) { + this._next = next; + }; + + Enumerator.prototype.next = function () { + return this._next(); + }; + + Enumerator.prototype[$iterator$] = function () { return this; } + + var Enumerable = Rx.internals.Enumerable = function (iterator) { + this._iterator = iterator; + }; + + Enumerable.prototype[$iterator$] = function () { + return this._iterator(); + }; + + Enumerable.prototype.concat = function () { + var sources = this; + return new AnonymousObservable(function (observer) { + var e; + try { + e = sources[$iterator$](); + } catch(err) { + observer.onError(); + return; + } + + var isDisposed, + subscription = new SerialDisposable(); + var cancelable = immediateScheduler.scheduleRecursive(function (self) { + var currentItem; + if (isDisposed) { return; } + + try { + currentItem = e.next(); + } catch (ex) { + observer.onError(ex); + return; + } + + if (currentItem.done) { + observer.onCompleted(); + return; + } + + // Check if promise + var currentValue = currentItem.value; + isPromise(currentValue) && (currentValue = observableFromPromise(currentValue)); + + var d = new SingleAssignmentDisposable(); + subscription.setDisposable(d); + d.setDisposable(currentValue.subscribe( + observer.onNext.bind(observer), + observer.onError.bind(observer), + function () { self(); }) + ); + }); + + return new CompositeDisposable(subscription, cancelable, disposableCreate(function () { + isDisposed = true; + })); + }); + }; + + Enumerable.prototype.catchException = function () { + var sources = this; + return new AnonymousObservable(function (observer) { + var e; + try { + e = sources[$iterator$](); + } catch(err) { + observer.onError(); + return; + } + + var isDisposed, + lastException, + subscription = new SerialDisposable(); + var cancelable = immediateScheduler.scheduleRecursive(function (self) { + if (isDisposed) { return; } + + var currentItem; + try { + currentItem = e.next(); + } catch (ex) { + observer.onError(ex); + return; + } + + if (currentItem.done) { + if (lastException) { + observer.onError(lastException); + } else { + observer.onCompleted(); + } + return; + } + + // Check if promise + var currentValue = currentItem.value; + isPromise(currentValue) && (currentValue = observableFromPromise(currentValue)); + + var d = new SingleAssignmentDisposable(); + subscription.setDisposable(d); + d.setDisposable(currentValue.subscribe( + observer.onNext.bind(observer), + function (exn) { + lastException = exn; + self(); + }, + observer.onCompleted.bind(observer))); + }); + return new CompositeDisposable(subscription, cancelable, disposableCreate(function () { + isDisposed = true; + })); + }); + }; + + var enumerableRepeat = Enumerable.repeat = function (value, repeatCount) { + if (repeatCount == null) { repeatCount = -1; } + return new Enumerable(function () { + var left = repeatCount; + return new Enumerator(function () { + if (left === 0) { return doneEnumerator; } + if (left > 0) { left--; } + return { done: false, value: value }; + }); + }); + }; + + var enumerableFor = Enumerable.forEach = function (source, selector, thisArg) { + selector || (selector = identity); + return new Enumerable(function () { + var index = -1; + return new Enumerator( + function () { + return ++index < source.length ? + { done: false, value: selector.call(thisArg, source[index], index, source) } : + doneEnumerator; + }); + }); + }; + + /** + * Supports push-style iteration over an observable sequence. + */ + var Observer = Rx.Observer = function () { }; + + /** + * Creates a notification callback from an observer. + * + * @param observer Observer object. + * @returns The action that forwards its input notification to the underlying observer. + */ + Observer.prototype.toNotifier = function () { + var observer = this; + return function (n) { + return n.accept(observer); + }; + }; + + /** + * Hides the identity of an observer. + + * @returns An observer that hides the identity of the specified observer. + */ + Observer.prototype.asObserver = function () { + return new AnonymousObserver(this.onNext.bind(this), this.onError.bind(this), this.onCompleted.bind(this)); + }; + + /** + * Checks access to the observer for grammar violations. This includes checking for multiple OnError or OnCompleted calls, as well as reentrancy in any of the observer methods. + * If a violation is detected, an Error is thrown from the offending observer method call. + * + * @returns An observer that checks callbacks invocations against the observer grammar and, if the checks pass, forwards those to the specified observer. + */ + Observer.prototype.checked = function () { return new CheckedObserver(this); }; + + /** + * Creates an observer from the specified OnNext, along with optional OnError, and OnCompleted actions. + * + * @static + * @memberOf Observer + * @param {Function} [onNext] Observer's OnNext action implementation. + * @param {Function} [onError] Observer's OnError action implementation. + * @param {Function} [onCompleted] Observer's OnCompleted action implementation. + * @returns {Observer} The observer object implemented using the given actions. + */ + var observerCreate = Observer.create = function (onNext, onError, onCompleted) { + onNext || (onNext = noop); + onError || (onError = defaultError); + onCompleted || (onCompleted = noop); + return new AnonymousObserver(onNext, onError, onCompleted); + }; + + /** + * Creates an observer from a notification callback. + * + * @static + * @memberOf Observer + * @param {Function} handler Action that handles a notification. + * @returns The observer object that invokes the specified handler using a notification corresponding to each message it receives. + */ + Observer.fromNotifier = function (handler) { + return new AnonymousObserver(function (x) { + return handler(notificationCreateOnNext(x)); + }, function (exception) { + return handler(notificationCreateOnError(exception)); + }, function () { + return handler(notificationCreateOnCompleted()); + }); + }; + + /** + * Schedules the invocation of observer methods on the given scheduler. + * @param {Scheduler} scheduler Scheduler to schedule observer messages on. + * @returns {Observer} Observer whose messages are scheduled on the given scheduler. + */ + Observer.notifyOn = function (scheduler) { + return new ObserveOnObserver(scheduler, this); + }; + + /** + * Abstract base class for implementations of the Observer class. + * This base class enforces the grammar of observers where OnError and OnCompleted are terminal messages. + */ + var AbstractObserver = Rx.internals.AbstractObserver = (function (_super) { + inherits(AbstractObserver, _super); + + /** + * Creates a new observer in a non-stopped state. + * + * @constructor + */ + function AbstractObserver() { + this.isStopped = false; + _super.call(this); + } + + /** + * Notifies the observer of a new element in the sequence. + * + * @memberOf AbstractObserver + * @param {Any} value Next element in the sequence. + */ + AbstractObserver.prototype.onNext = function (value) { + if (!this.isStopped) { + this.next(value); + } + }; + + /** + * Notifies the observer that an exception has occurred. + * + * @memberOf AbstractObserver + * @param {Any} error The error that has occurred. + */ + AbstractObserver.prototype.onError = function (error) { + if (!this.isStopped) { + this.isStopped = true; + this.error(error); + } + }; + + /** + * Notifies the observer of the end of the sequence. + */ + AbstractObserver.prototype.onCompleted = function () { + if (!this.isStopped) { + this.isStopped = true; + this.completed(); + } + }; + + /** + * Disposes the observer, causing it to transition to the stopped state. + */ + AbstractObserver.prototype.dispose = function () { + this.isStopped = true; + }; + + AbstractObserver.prototype.fail = function (e) { + if (!this.isStopped) { + this.isStopped = true; + this.error(e); + return true; + } + + return false; + }; + + return AbstractObserver; + }(Observer)); + + /** + * Class to create an Observer instance from delegate-based implementations of the on* methods. + */ + var AnonymousObserver = Rx.AnonymousObserver = (function (_super) { + inherits(AnonymousObserver, _super); + + /** + * Creates an observer from the specified OnNext, OnError, and OnCompleted actions. + * @param {Any} onNext Observer's OnNext action implementation. + * @param {Any} onError Observer's OnError action implementation. + * @param {Any} onCompleted Observer's OnCompleted action implementation. + */ + function AnonymousObserver(onNext, onError, onCompleted) { + _super.call(this); + this._onNext = onNext; + this._onError = onError; + this._onCompleted = onCompleted; + } + + /** + * Calls the onNext action. + * @param {Any} value Next element in the sequence. + */ + AnonymousObserver.prototype.next = function (value) { + this._onNext(value); + }; + + /** + * Calls the onError action. + * @param {Any} error The error that has occurred. + */ + AnonymousObserver.prototype.error = function (exception) { + this._onError(exception); + }; + + /** + * Calls the onCompleted action. + */ + AnonymousObserver.prototype.completed = function () { + this._onCompleted(); + }; + + return AnonymousObserver; + }(AbstractObserver)); + + var CheckedObserver = (function (_super) { + inherits(CheckedObserver, _super); + + function CheckedObserver(observer) { + _super.call(this); + this._observer = observer; + this._state = 0; // 0 - idle, 1 - busy, 2 - done + } + + var CheckedObserverPrototype = CheckedObserver.prototype; + + CheckedObserverPrototype.onNext = function (value) { + this.checkAccess(); + try { + this._observer.onNext(value); + } catch (e) { + throw e; + } finally { + this._state = 0; + } + }; + + CheckedObserverPrototype.onError = function (err) { + this.checkAccess(); + try { + this._observer.onError(err); + } catch (e) { + throw e; + } finally { + this._state = 2; + } + }; + + CheckedObserverPrototype.onCompleted = function () { + this.checkAccess(); + try { + this._observer.onCompleted(); + } catch (e) { + throw e; + } finally { + this._state = 2; + } + }; + + CheckedObserverPrototype.checkAccess = function () { + if (this._state === 1) { throw new Error('Re-entrancy detected'); } + if (this._state === 2) { throw new Error('Observer completed'); } + if (this._state === 0) { this._state = 1; } + }; + + return CheckedObserver; + }(Observer)); + + var ScheduledObserver = Rx.internals.ScheduledObserver = (function (_super) { + inherits(ScheduledObserver, _super); + + function ScheduledObserver(scheduler, observer) { + _super.call(this); + this.scheduler = scheduler; + this.observer = observer; + this.isAcquired = false; + this.hasFaulted = false; + this.queue = []; + this.disposable = new SerialDisposable(); + } + + ScheduledObserver.prototype.next = function (value) { + var self = this; + this.queue.push(function () { + self.observer.onNext(value); + }); + }; + + ScheduledObserver.prototype.error = function (exception) { + var self = this; + this.queue.push(function () { + self.observer.onError(exception); + }); + }; + + ScheduledObserver.prototype.completed = function () { + var self = this; + this.queue.push(function () { + self.observer.onCompleted(); + }); + }; + + ScheduledObserver.prototype.ensureActive = function () { + var isOwner = false, parent = this; + if (!this.hasFaulted && this.queue.length > 0) { + isOwner = !this.isAcquired; + this.isAcquired = true; + } + if (isOwner) { + this.disposable.setDisposable(this.scheduler.scheduleRecursive(function (self) { + var work; + if (parent.queue.length > 0) { + work = parent.queue.shift(); + } else { + parent.isAcquired = false; + return; + } + try { + work(); + } catch (ex) { + parent.queue = []; + parent.hasFaulted = true; + throw ex; + } + self(); + })); + } + }; + + ScheduledObserver.prototype.dispose = function () { + _super.prototype.dispose.call(this); + this.disposable.dispose(); + }; + + return ScheduledObserver; + }(AbstractObserver)); + + /** @private */ + var ObserveOnObserver = (function (_super) { + inherits(ObserveOnObserver, _super); + + /** @private */ + function ObserveOnObserver() { + _super.apply(this, arguments); + } + + /** @private */ + ObserveOnObserver.prototype.next = function (value) { + _super.prototype.next.call(this, value); + this.ensureActive(); + }; + + /** @private */ + ObserveOnObserver.prototype.error = function (e) { + _super.prototype.error.call(this, e); + this.ensureActive(); + }; + + /** @private */ + ObserveOnObserver.prototype.completed = function () { + _super.prototype.completed.call(this); + this.ensureActive(); + }; + + return ObserveOnObserver; + })(ScheduledObserver); + + var observableProto; + + /** + * Represents a push-style collection. + */ + var Observable = Rx.Observable = (function () { + + function Observable(subscribe) { + this._subscribe = subscribe; + } + + observableProto = Observable.prototype; + + /** + * Subscribes an observer to the observable sequence. + * + * @example + * 1 - source.subscribe(); + * 2 - source.subscribe(observer); + * 3 - source.subscribe(function (x) { console.log(x); }); + * 4 - source.subscribe(function (x) { console.log(x); }, function (err) { console.log(err); }); + * 5 - source.subscribe(function (x) { console.log(x); }, function (err) { console.log(err); }, function () { console.log('done'); }); + * @param {Mixed} [observerOrOnNext] The object that is to receive notifications or an action to invoke for each element in the observable sequence. + * @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence. + * @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence. + * @returns {Diposable} The source sequence whose subscriptions and unsubscriptions happen on the specified scheduler. + */ + observableProto.subscribe = observableProto.forEach = function (observerOrOnNext, onError, onCompleted) { + var subscriber = typeof observerOrOnNext === 'object' ? + observerOrOnNext : + observerCreate(observerOrOnNext, onError, onCompleted); + + return this._subscribe(subscriber); + }; + + return Observable; + })(); + + /** + * Wraps the source sequence in order to run its observer callbacks on the specified scheduler. + * + * This only invokes observer callbacks on a scheduler. In case the subscription and/or unsubscription actions have side-effects + * that require to be run on a scheduler, use subscribeOn. + * + * @param {Scheduler} scheduler Scheduler to notify observers on. + * @returns {Observable} The source sequence whose observations happen on the specified scheduler. + */ + observableProto.observeOn = function (scheduler) { + var source = this; + return new AnonymousObservable(function (observer) { + return source.subscribe(new ObserveOnObserver(scheduler, observer)); + }); + }; + + /** + * Wraps the source sequence in order to run its subscription and unsubscription logic on the specified scheduler. This operation is not commonly used; + * see the remarks section for more information on the distinction between subscribeOn and observeOn. + + * This only performs the side-effects of subscription and unsubscription on the specified scheduler. In order to invoke observer + * callbacks on a scheduler, use observeOn. + + * @param {Scheduler} scheduler Scheduler to perform subscription and unsubscription actions on. + * @returns {Observable} The source sequence whose subscriptions and unsubscriptions happen on the specified scheduler. + */ + observableProto.subscribeOn = function (scheduler) { + var source = this; + return new AnonymousObservable(function (observer) { + var m = new SingleAssignmentDisposable(), d = new SerialDisposable(); + d.setDisposable(m); + m.setDisposable(scheduler.schedule(function () { + d.setDisposable(new ScheduledDisposable(scheduler, source.subscribe(observer))); + })); + return d; + }); + }; + + /** + * Converts a Promise to an Observable sequence + * @param {Promise} An ES6 Compliant promise. + * @returns {Observable} An Observable sequence which wraps the existing promise success and failure. + */ + var observableFromPromise = Observable.fromPromise = function (promise) { + return new AnonymousObservable(function (observer) { + promise.then( + function (value) { + observer.onNext(value); + observer.onCompleted(); + }, + function (reason) { + observer.onError(reason); + }); + + return function () { + if (promise && promise.abort) { + promise.abort(); + } + } + }); + }; + /* + * Converts an existing observable sequence to an ES6 Compatible Promise + * @example + * var promise = Rx.Observable.return(42).toPromise(RSVP.Promise); + * + * // With config + * Rx.config.Promise = RSVP.Promise; + * var promise = Rx.Observable.return(42).toPromise(); + * @param {Function} [promiseCtor] The constructor of the promise. If not provided, it looks for it in Rx.config.Promise. + * @returns {Promise} An ES6 compatible promise with the last value from the observable sequence. + */ + observableProto.toPromise = function (promiseCtor) { + promiseCtor || (promiseCtor = Rx.config.Promise); + if (!promiseCtor) { + throw new Error('Promise type not provided nor in Rx.config.Promise'); + } + var source = this; + return new promiseCtor(function (resolve, reject) { + // No cancellation can be done + var value, hasValue = false; + source.subscribe(function (v) { + value = v; + hasValue = true; + }, function (err) { + reject(err); + }, function () { + if (hasValue) { + resolve(value); + } + }); + }); + }; + /** + * Creates a list from an observable sequence. + * @returns An observable sequence containing a single element with a list containing all the elements of the source sequence. + */ + observableProto.toArray = function () { + var self = this; + return new AnonymousObservable(function(observer) { + var arr = []; + return self.subscribe( + arr.push.bind(arr), + observer.onError.bind(observer), + function () { + observer.onNext(arr); + observer.onCompleted(); + }); + }); + }; + + /** + * Creates an observable sequence from a specified subscribe method implementation. + * + * @example + * var res = Rx.Observable.create(function (observer) { return function () { } ); + * var res = Rx.Observable.create(function (observer) { return Rx.Disposable.empty; } ); + * var res = Rx.Observable.create(function (observer) { } ); + * + * @param {Function} subscribe Implementation of the resulting observable sequence's subscribe method, returning a function that will be wrapped in a Disposable. + * @returns {Observable} The observable sequence with the specified implementation for the Subscribe method. + */ + Observable.create = Observable.createWithDisposable = function (subscribe) { + return new AnonymousObservable(subscribe); + }; + + /** + * Returns an observable sequence that invokes the specified factory function whenever a new observer subscribes. + * + * @example + * var res = Rx.Observable.defer(function () { return Rx.Observable.fromArray([1,2,3]); }); + * @param {Function} observableFactory Observable factory function to invoke for each observer that subscribes to the resulting sequence or Promise. + * @returns {Observable} An observable sequence whose observers trigger an invocation of the given observable factory function. + */ + var observableDefer = Observable.defer = function (observableFactory) { + return new AnonymousObservable(function (observer) { + var result; + try { + result = observableFactory(); + } catch (e) { + return observableThrow(e).subscribe(observer); + } + isPromise(result) && (result = observableFromPromise(result)); + return result.subscribe(observer); + }); + }; + + /** + * Returns an empty observable sequence, using the specified scheduler to send out the single OnCompleted message. + * + * @example + * var res = Rx.Observable.empty(); + * var res = Rx.Observable.empty(Rx.Scheduler.timeout); + * @param {Scheduler} [scheduler] Scheduler to send the termination call on. + * @returns {Observable} An observable sequence with no elements. + */ + var observableEmpty = Observable.empty = function (scheduler) { + scheduler || (scheduler = immediateScheduler); + return new AnonymousObservable(function (observer) { + return scheduler.schedule(function () { + observer.onCompleted(); + }); + }); + }; + + /** + * Converts an array to an observable sequence, using an optional scheduler to enumerate the array. + * + * @example + * var res = Rx.Observable.fromArray([1,2,3]); + * var res = Rx.Observable.fromArray([1,2,3], Rx.Scheduler.timeout); + * @param {Scheduler} [scheduler] Scheduler to run the enumeration of the input sequence on. + * @returns {Observable} The observable sequence whose elements are pulled from the given enumerable sequence. + */ + var observableFromArray = Observable.fromArray = function (array, scheduler) { + scheduler || (scheduler = currentThreadScheduler); + return new AnonymousObservable(function (observer) { + var count = 0, len = array.length; + return scheduler.scheduleRecursive(function (self) { + if (count < len) { + observer.onNext(array[count++]); + self(); + } else { + observer.onCompleted(); + } + }); + }); + }; + + /** + * Converts an iterable into an Observable sequence + * + * @example + * var res = Rx.Observable.fromIterable(new Map()); + * var res = Rx.Observable.fromIterable(new Set(), Rx.Scheduler.timeout); + * @param {Scheduler} [scheduler] Scheduler to run the enumeration of the input sequence on. + * @returns {Observable} The observable sequence whose elements are pulled from the given generator sequence. + */ + Observable.fromIterable = function (iterable, scheduler) { + scheduler || (scheduler = currentThreadScheduler); + return new AnonymousObservable(function (observer) { + var iterator; + try { + iterator = iterable[$iterator$](); + } catch (e) { + observer.onError(e); + return; + } + + return scheduler.scheduleRecursive(function (self) { + var next; + try { + next = iterator.next(); + } catch (err) { + observer.onError(err); + return; + } + + if (next.done) { + observer.onCompleted(); + } else { + observer.onNext(next.value); + self(); + } + }); + }); + }; + + /** + * 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) { + scheduler || (scheduler = currentThreadScheduler); + return new AnonymousObservable(function (observer) { + var first = true, state = initialState; + return scheduler.scheduleRecursive(function (self) { + var hasResult, result; + try { + if (first) { + first = false; + } else { + state = iterate(state); + } + hasResult = condition(state); + if (hasResult) { + result = resultSelector(state); + } + } catch (exception) { + observer.onError(exception); + return; + } + if (hasResult) { + observer.onNext(result); + self(); + } else { + observer.onCompleted(); + } + }); + }); + }; + + /** + * Returns a non-terminating observable sequence, which can be used to denote an infinite duration (e.g. when using reactive joins). + * @returns {Observable} An observable sequence whose observers will never get called. + */ + var observableNever = Observable.never = function () { + return new AnonymousObservable(function () { + return disposableEmpty; + }); + }; + + /** + * This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments. + * @example + * var res = Rx.Observable.of(1,2,3); + * @returns {Observable} The observable sequence whose elements are pulled from the given arguments. + */ + Observable.of = function () { + var len = arguments.length, args = new Array(len); + for(var i = 0; i < len; i++) { args[i] = arguments[i]; } + return observableFromArray(args); + }; + + /** + * This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments. + * @example + * var res = Rx.Observable.of(1,2,3); + * @param {Scheduler} scheduler A scheduler to use for scheduling the arguments. + * @returns {Observable} The observable sequence whose elements are pulled from the given arguments. + */ + var observableOf = Observable.ofWithScheduler = function (scheduler) { + var len = arguments.length - 1, args = new Array(len); + for(var i = 0; i < len; i++) { args[i] = arguments[i + 1]; } + return observableFromArray(args, scheduler); + }; + + /** + * Generates an observable sequence of integral numbers within a specified range, using the specified scheduler to send out observer messages. + * + * @example + * var res = Rx.Observable.range(0, 10); + * var res = Rx.Observable.range(0, 10, Rx.Scheduler.timeout); + * @param {Number} start The value of the first integer in the sequence. + * @param {Number} count The number of sequential integers to generate. + * @param {Scheduler} [scheduler] Scheduler to run the generator loop on. If not specified, defaults to Scheduler.currentThread. + * @returns {Observable} An observable sequence that contains a range of sequential integral numbers. + */ + Observable.range = function (start, count, scheduler) { + scheduler || (scheduler = currentThreadScheduler); + return new AnonymousObservable(function (observer) { + return scheduler.scheduleRecursiveWithState(0, function (i, self) { + if (i < count) { + observer.onNext(start + i); + self(i + 1); + } else { + observer.onCompleted(); + } + }); + }); + }; + + /** + * Generates an observable sequence that repeats the given element the specified number of times, using the specified scheduler to send out observer messages. + * + * @example + * var res = Rx.Observable.repeat(42); + * var res = Rx.Observable.repeat(42, 4); + * 3 - res = Rx.Observable.repeat(42, 4, Rx.Scheduler.timeout); + * 4 - res = Rx.Observable.repeat(42, null, Rx.Scheduler.timeout); + * @param {Mixed} value Element to repeat. + * @param {Number} repeatCount [Optiona] Number of times to repeat the element. If not specified, repeats indefinitely. + * @param {Scheduler} scheduler Scheduler to run the producer loop on. If not specified, defaults to Scheduler.immediate. + * @returns {Observable} An observable sequence that repeats the given element the specified number of times. + */ + Observable.repeat = function (value, repeatCount, scheduler) { + scheduler || (scheduler = currentThreadScheduler); + if (repeatCount == null) { + repeatCount = -1; + } + return observableReturn(value, scheduler).repeat(repeatCount); + }; + + /** + * Returns an observable sequence that contains a single element, using the specified scheduler to send out observer messages. + * There is an alias called 'just', and 'returnValue' for browsers 0) { + s = q.shift(); + subscribe(s); + } else { + activeCount--; + if (isStopped && activeCount === 0) { + observer.onCompleted(); + } + } + })); + }; + group.add(sources.subscribe(function (innerSource) { + if (activeCount < maxConcurrentOrOther) { + activeCount++; + subscribe(innerSource); + } else { + q.push(innerSource); + } + }, observer.onError.bind(observer), function () { + isStopped = true; + if (activeCount === 0) { + observer.onCompleted(); + } + })); + return group; + }); + }; + + /** + * Merges all the observable sequences into a single observable sequence. + * The scheduler is optional and if not specified, the immediate scheduler is used. + * + * @example + * 1 - merged = Rx.Observable.merge(xs, ys, zs); + * 2 - merged = Rx.Observable.merge([xs, ys, zs]); + * 3 - merged = Rx.Observable.merge(scheduler, xs, ys, zs); + * 4 - merged = Rx.Observable.merge(scheduler, [xs, ys, zs]); + * @returns {Observable} The observable sequence that merges the elements of the observable sequences. + */ + var observableMerge = Observable.merge = function () { + var scheduler, sources; + if (!arguments[0]) { + scheduler = immediateScheduler; + sources = slice.call(arguments, 1); + } else if (arguments[0].now) { + scheduler = arguments[0]; + sources = slice.call(arguments, 1); + } else { + scheduler = immediateScheduler; + sources = slice.call(arguments, 0); + } + if (Array.isArray(sources[0])) { + sources = sources[0]; + } + return observableFromArray(sources, scheduler).mergeObservable(); + }; + + /** + * Merges an observable sequence of observable sequences into an observable sequence. + * @returns {Observable} The observable sequence that merges the elements of the inner sequences. + */ + observableProto.mergeObservable = observableProto.mergeAll =function () { + var sources = this; + return new AnonymousObservable(function (observer) { + var group = new CompositeDisposable(), + isStopped = false, + m = new SingleAssignmentDisposable(); + + group.add(m); + m.setDisposable(sources.subscribe(function (innerSource) { + var innerSubscription = new SingleAssignmentDisposable(); + group.add(innerSubscription); + + // Check if Promise or Observable + if (isPromise(innerSource)) { + innerSource = observableFromPromise(innerSource); + } + + innerSubscription.setDisposable(innerSource.subscribe(function (x) { + observer.onNext(x); + }, observer.onError.bind(observer), function () { + group.remove(innerSubscription); + if (isStopped && group.length === 1) { observer.onCompleted(); } + })); + }, observer.onError.bind(observer), function () { + isStopped = true; + if (group.length === 1) { observer.onCompleted(); } + })); + return group; + }); + }; + + /** + * Continues an observable sequence that is terminated normally or by an exception with the next observable sequence. + * @param {Observable} second Second observable sequence used to produce results after the first sequence terminates. + * @returns {Observable} An observable sequence that concatenates the first and second sequence, even if the first sequence terminates exceptionally. + */ + observableProto.onErrorResumeNext = function (second) { + if (!second) { + throw new Error('Second observable is required'); + } + return onErrorResumeNext([this, second]); + }; + + /** + * Continues an observable sequence that is terminated normally or by an exception with the next observable sequence. + * + * @example + * 1 - res = Rx.Observable.onErrorResumeNext(xs, ys, zs); + * 1 - res = Rx.Observable.onErrorResumeNext([xs, ys, zs]); + * @returns {Observable} An observable sequence that concatenates the source sequences, even if a sequence terminates exceptionally. + */ + var onErrorResumeNext = Observable.onErrorResumeNext = function () { + var sources = argsOrArray(arguments, 0); + return new AnonymousObservable(function (observer) { + var pos = 0, subscription = new SerialDisposable(), + cancelable = immediateScheduler.scheduleRecursive(function (self) { + var current, d; + if (pos < sources.length) { + current = sources[pos++]; + isPromise(current) && (current = observableFromPromise(current)); + d = new SingleAssignmentDisposable(); + subscription.setDisposable(d); + d.setDisposable(current.subscribe(observer.onNext.bind(observer), function () { + self(); + }, function () { + self(); + })); + } else { + observer.onCompleted(); + } + }); + return new CompositeDisposable(subscription, cancelable); + }); + }; + + /** + * Returns the values from the source observable sequence only after the other observable sequence produces a value. + * @param {Observable | Promise} other The observable sequence or Promise that triggers propagation of elements of the source sequence. + * @returns {Observable} An observable sequence containing the elements of the source sequence starting from the point the other sequence triggered propagation. + */ + observableProto.skipUntil = function (other) { + var source = this; + return new AnonymousObservable(function (observer) { + var isOpen = false; + var disposables = new CompositeDisposable(source.subscribe(function (left) { + isOpen && observer.onNext(left); + }, observer.onError.bind(observer), function () { + isOpen && observer.onCompleted(); + })); + + isPromise(other) && (other = observableFromPromise(other)); + + var rightSubscription = new SingleAssignmentDisposable(); + disposables.add(rightSubscription); + rightSubscription.setDisposable(other.subscribe(function () { + isOpen = true; + rightSubscription.dispose(); + }, observer.onError.bind(observer), function () { + rightSubscription.dispose(); + })); + + return disposables; + }); + }; + + /** + * Transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence. + * @returns {Observable} The observable sequence that at any point in time produces the elements of the most recent inner observable sequence that has been received. + */ + observableProto['switch'] = observableProto.switchLatest = function () { + var sources = this; + return new AnonymousObservable(function (observer) { + var hasLatest = false, + innerSubscription = new SerialDisposable(), + isStopped = false, + latest = 0, + subscription = sources.subscribe(function (innerSource) { + var d = new SingleAssignmentDisposable(), id = ++latest; + hasLatest = true; + innerSubscription.setDisposable(d); + + // Check if Promise or Observable + if (isPromise(innerSource)) { + innerSource = observableFromPromise(innerSource); + } + + d.setDisposable(innerSource.subscribe(function (x) { + if (latest === id) { + observer.onNext(x); + } + }, function (e) { + if (latest === id) { + observer.onError(e); + } + }, function () { + if (latest === id) { + hasLatest = false; + if (isStopped) { + observer.onCompleted(); + } + } + })); + }, observer.onError.bind(observer), function () { + isStopped = true; + if (!hasLatest) { + observer.onCompleted(); + } + }); + return new CompositeDisposable(subscription, innerSubscription); + }); + }; + + /** + * Returns the values from the source observable sequence until the other observable sequence produces a value. + * @param {Observable | Promise} other Observable sequence or Promise that terminates propagation of elements of the source sequence. + * @returns {Observable} An observable sequence containing the elements of the source sequence up to the point the other sequence interrupted further propagation. + */ + observableProto.takeUntil = function (other) { + var source = this; + return new AnonymousObservable(function (observer) { + isPromise(other) && (other = observableFromPromise(other)); + return new CompositeDisposable( + source.subscribe(observer), + other.subscribe(observer.onCompleted.bind(observer), observer.onError.bind(observer), noop) + ); + }); + }; + + function zipArray(second, resultSelector) { + var first = this; + return new AnonymousObservable(function (observer) { + var index = 0, len = second.length; + return first.subscribe(function (left) { + if (index < len) { + var right = second[index++], result; + try { + result = resultSelector(left, right); + } catch (e) { + observer.onError(e); + return; + } + observer.onNext(result); + } else { + observer.onCompleted(); + } + }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); + }); + } + + /** + * Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences or an array have produced an element at a corresponding index. + * The last element in the arguments must be a function to invoke for each series of elements at corresponding indexes in the sources. + * + * @example + * 1 - res = obs1.zip(obs2, fn); + * 1 - res = x1.zip([1,2,3], fn); + * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + observableProto.zip = function () { + if (Array.isArray(arguments[0])) { + return zipArray.apply(this, arguments); + } + var parent = this, sources = slice.call(arguments), resultSelector = sources.pop(); + sources.unshift(parent); + return new AnonymousObservable(function (observer) { + var n = sources.length, + queues = arrayInitialize(n, function () { return []; }), + isDone = arrayInitialize(n, function () { return false; }); + + function next(i) { + var res, queuedValues; + if (queues.every(function (x) { return x.length > 0; })) { + try { + queuedValues = queues.map(function (x) { return x.shift(); }); + res = resultSelector.apply(parent, queuedValues); + } catch (ex) { + observer.onError(ex); + return; + } + observer.onNext(res); + } else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) { + observer.onCompleted(); + } + }; + + function done(i) { + isDone[i] = true; + if (isDone.every(function (x) { return x; })) { + observer.onCompleted(); + } + } + + var subscriptions = new Array(n); + for (var idx = 0; idx < n; idx++) { + (function (i) { + var source = sources[i], sad = new SingleAssignmentDisposable(); + isPromise(source) && (source = observableFromPromise(source)); + sad.setDisposable(source.subscribe(function (x) { + queues[i].push(x); + next(i); + }, observer.onError.bind(observer), function () { + done(i); + })); + subscriptions[i] = sad; + })(idx); + } + + return new CompositeDisposable(subscriptions); + }); + }; + /** + * Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index. + * @param arguments Observable sources. + * @param {Function} resultSelector Function to invoke for each series of elements at corresponding indexes in the sources. + * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + Observable.zip = function () { + var args = slice.call(arguments, 0), + first = args.shift(); + return first.zip.apply(first, args); + }; + + /** + * Merges the specified observable sequences into one observable sequence by emitting a list with the elements of the observable sequences at corresponding indexes. + * @param arguments Observable sources. + * @returns {Observable} An observable sequence containing lists of elements at corresponding indexes. + */ + Observable.zipArray = function () { + var sources = argsOrArray(arguments, 0); + return new AnonymousObservable(function (observer) { + var n = sources.length, + queues = arrayInitialize(n, function () { return []; }), + isDone = arrayInitialize(n, function () { return false; }); + + function next(i) { + if (queues.every(function (x) { return x.length > 0; })) { + var res = queues.map(function (x) { return x.shift(); }); + observer.onNext(res); + } else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) { + observer.onCompleted(); + return; + } + }; + + function done(i) { + isDone[i] = true; + if (isDone.every(identity)) { + observer.onCompleted(); + return; + } + } + + var subscriptions = new Array(n); + for (var idx = 0; idx < n; idx++) { + (function (i) { + subscriptions[i] = new SingleAssignmentDisposable(); + subscriptions[i].setDisposable(sources[i].subscribe(function (x) { + queues[i].push(x); + next(i); + }, observer.onError.bind(observer), function () { + done(i); + })); + })(idx); + } + + var compositeDisposable = new CompositeDisposable(subscriptions); + compositeDisposable.add(disposableCreate(function () { + for (var qIdx = 0, qLen = queues.length; qIdx < qLen; qIdx++) { + queues[qIdx] = []; + } + })); + return compositeDisposable; + }); + }; + + /** + * Hides the identity of an observable sequence. + * @returns {Observable} An observable sequence that hides the identity of the source sequence. + */ + observableProto.asObservable = function () { + var source = this; + return new AnonymousObservable(function (observer) { + return source.subscribe(observer); + }); + }; + + /** + * Projects each element of an observable sequence into zero or more buffers which are produced based on element count information. + * + * @example + * var res = xs.bufferWithCount(10); + * var res = xs.bufferWithCount(10, 1); + * @param {Number} count Length of each buffer. + * @param {Number} [skip] Number of elements to skip between creation of consecutive buffers. If not provided, defaults to the count. + * @returns {Observable} An observable sequence of buffers. + */ + observableProto.bufferWithCount = function (count, skip) { + if (typeof skip !== 'number') { + skip = count; + } + return this.windowWithCount(count, skip).selectMany(function (x) { + return x.toArray(); + }).where(function (x) { + return x.length > 0; + }); + }; + + /** + * Dematerializes the explicit notification values of an observable sequence as implicit notifications. + * @returns {Observable} An observable sequence exhibiting the behavior corresponding to the source sequence's notification values. + */ + observableProto.dematerialize = function () { + var source = this; + return new AnonymousObservable(function (observer) { + return source.subscribe(function (x) { + return x.accept(observer); + }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); + }); + }; + + /** + * Returns an observable sequence that contains only distinct contiguous elements according to the keySelector and the comparer. + * + * var obs = observable.distinctUntilChanged(); + * var obs = observable.distinctUntilChanged(function (x) { return x.id; }); + * var obs = observable.distinctUntilChanged(function (x) { return x.id; }, function (x, y) { return x === y; }); + * + * @param {Function} [keySelector] A function to compute the comparison key for each element. If not provided, it projects the value. + * @param {Function} [comparer] Equality comparer for computed key values. If not provided, defaults to an equality comparer function. + * @returns {Observable} An observable sequence only containing the distinct contiguous elements, based on a computed key value, from the source sequence. + */ + observableProto.distinctUntilChanged = function (keySelector, comparer) { + var source = this; + keySelector || (keySelector = identity); + comparer || (comparer = defaultComparer); + return new AnonymousObservable(function (observer) { + var hasCurrentKey = false, currentKey; + return source.subscribe(function (value) { + var comparerEquals = false, key; + try { + key = keySelector(value); + } catch (exception) { + observer.onError(exception); + return; + } + if (hasCurrentKey) { + try { + comparerEquals = comparer(currentKey, key); + } catch (exception) { + observer.onError(exception); + return; + } + } + if (!hasCurrentKey || !comparerEquals) { + hasCurrentKey = true; + currentKey = key; + observer.onNext(value); + } + }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); + }); + }; + + /** + * Invokes an action for each element in the observable sequence and invokes an action upon graceful or exceptional termination of the observable sequence. + * This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline. + * + * @example + * var res = observable.doAction(observer); + * var res = observable.doAction(onNext); + * var res = observable.doAction(onNext, onError); + * var res = observable.doAction(onNext, onError, onCompleted); + * @param {Mixed} observerOrOnNext Action to invoke for each element in the observable sequence or an observer. + * @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function. + * @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function. + * @returns {Observable} The source sequence with the side-effecting behavior applied. + */ + observableProto['do'] = observableProto.doAction = function (observerOrOnNext, onError, onCompleted) { + var source = this, onNextFunc; + if (typeof observerOrOnNext === 'function') { + onNextFunc = observerOrOnNext; + } else { + onNextFunc = observerOrOnNext.onNext.bind(observerOrOnNext); + onError = observerOrOnNext.onError.bind(observerOrOnNext); + onCompleted = observerOrOnNext.onCompleted.bind(observerOrOnNext); + } + return new AnonymousObservable(function (observer) { + return source.subscribe(function (x) { + try { + onNextFunc(x); + } catch (e) { + observer.onError(e); + } + observer.onNext(x); + }, function (exception) { + if (!onError) { + observer.onError(exception); + } else { + try { + onError(exception); + } catch (e) { + observer.onError(e); + } + observer.onError(exception); + } + }, function () { + if (!onCompleted) { + observer.onCompleted(); + } else { + try { + onCompleted(); + } catch (e) { + observer.onError(e); + } + observer.onCompleted(); + } + }); + }); + }; + + /** + * Invokes a specified action after the source observable sequence terminates gracefully or exceptionally. + * + * @example + * var res = observable.finallyAction(function () { console.log('sequence ended'; }); + * @param {Function} finallyAction Action to invoke after the source observable sequence terminates. + * @returns {Observable} Source sequence with the action-invoking termination behavior applied. + */ + observableProto['finally'] = observableProto.finallyAction = function (action) { + var source = this; + return new AnonymousObservable(function (observer) { + var subscription; + try { + subscription = source.subscribe(observer); + } catch (e) { + action(); + throw e; + } + return disposableCreate(function () { + try { + subscription.dispose(); + } catch (e) { + throw e; + } finally { + action(); + } + }); + }); + }; + + /** + * Ignores all elements in an observable sequence leaving only the termination messages. + * @returns {Observable} An empty observable sequence that signals termination, successful or exceptional, of the source sequence. + */ + observableProto.ignoreElements = function () { + var source = this; + return new AnonymousObservable(function (observer) { + return source.subscribe(noop, observer.onError.bind(observer), observer.onCompleted.bind(observer)); + }); + }; + + /** + * Materializes the implicit notifications of an observable sequence as explicit notification values. + * @returns {Observable} An observable sequence containing the materialized notification values from the source sequence. + */ + observableProto.materialize = function () { + var source = this; + return new AnonymousObservable(function (observer) { + return source.subscribe(function (value) { + observer.onNext(notificationCreateOnNext(value)); + }, function (e) { + observer.onNext(notificationCreateOnError(e)); + observer.onCompleted(); + }, function () { + observer.onNext(notificationCreateOnCompleted()); + observer.onCompleted(); + }); + }); + }; + + /** + * Repeats the observable sequence a specified number of times. If the repeat count is not specified, the sequence repeats indefinitely. + * + * @example + * var res = repeated = source.repeat(); + * var res = repeated = source.repeat(42); + * @param {Number} [repeatCount] Number of times to repeat the sequence. If not provided, repeats the sequence indefinitely. + * @returns {Observable} The observable sequence producing the elements of the given sequence repeatedly. + */ + observableProto.repeat = function (repeatCount) { + return enumerableRepeat(this, repeatCount).concat(); + }; + + /** + * Repeats the source observable sequence the specified number of times or until it successfully terminates. If the retry count is not specified, it retries indefinitely. + * + * @example + * var res = retried = retry.repeat(); + * var res = retried = retry.repeat(42); + * @param {Number} [retryCount] Number of times to retry the sequence. If not provided, retry the sequence indefinitely. + * @returns {Observable} An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully. + */ + observableProto.retry = function (retryCount) { + return enumerableRepeat(this, retryCount).catchException(); + }; + + /** + * Applies an accumulator function over an observable sequence and returns each intermediate result. The optional seed value is used as the initial accumulator value. + * For aggregation behavior with no intermediate results, see Observable.aggregate. + * @example + * var res = source.scan(function (acc, x) { return acc + x; }); + * var res = source.scan(0, function (acc, x) { return acc + x; }); + * @param {Mixed} [seed] The initial accumulator value. + * @param {Function} accumulator An accumulator function to be invoked on each element. + * @returns {Observable} An observable sequence containing the accumulated values. + */ + observableProto.scan = function () { + var hasSeed = false, seed, accumulator, source = this; + if (arguments.length === 2) { + hasSeed = true; + seed = arguments[0]; + accumulator = arguments[1]; + } else { + accumulator = arguments[0]; + } + return new AnonymousObservable(function (observer) { + var hasAccumulation, accumulation, hasValue; + return source.subscribe ( + function (x) { + try { + if (!hasValue) { + hasValue = true; + } + + if (hasAccumulation) { + accumulation = accumulator(accumulation, x); + } else { + accumulation = hasSeed ? accumulator(seed, x) : x; + hasAccumulation = true; + } + } catch (e) { + observer.onError(e); + return; + } + + observer.onNext(accumulation); + }, + observer.onError.bind(observer), + function () { + if (!hasValue && hasSeed) { + observer.onNext(seed); + } + observer.onCompleted(); + } + ); + }); + }; + + /** + * Bypasses a specified number of elements at the end of an observable sequence. + * @description + * This operator accumulates a queue with a length enough to store the first `count` elements. As more elements are + * received, elements are taken from the front of the queue and produced on the result sequence. This causes elements to be delayed. + * @param count Number of elements to bypass at the end of the source sequence. + * @returns {Observable} An observable sequence containing the source sequence elements except for the bypassed ones at the end. + */ + observableProto.skipLast = function (count) { + var source = this; + return new AnonymousObservable(function (observer) { + var q = []; + return source.subscribe(function (x) { + q.push(x); + if (q.length > count) { + observer.onNext(q.shift()); + } + }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); + }); + }; + + /** + * Prepends a sequence of values to an observable sequence with an optional scheduler and an argument list of values to prepend. + * + * var res = source.startWith(1, 2, 3); + * var res = source.startWith(Rx.Scheduler.timeout, 1, 2, 3); + * + * @memberOf Observable# + * @returns {Observable} The source sequence prepended with the specified values. + */ + observableProto.startWith = function () { + var values, scheduler, start = 0; + if (!!arguments.length && 'now' in Object(arguments[0])) { + scheduler = arguments[0]; + start = 1; + } else { + scheduler = immediateScheduler; + } + values = slice.call(arguments, start); + return enumerableFor([observableFromArray(values, scheduler), this]).concat(); + }; + + /** + * Returns a specified number of contiguous elements from the end of an observable sequence, using an optional scheduler to drain the queue. + * + * @example + * var res = source.takeLast(5); + * var res = source.takeLast(5, Rx.Scheduler.timeout); + * + * @description + * This operator accumulates a buffer with a length enough to store elements count elements. Upon completion of + * the source sequence, this buffer is drained on the result sequence. This causes the elements to be delayed. + * @param {Number} count Number of elements to take from the end of the source sequence. + * @param {Scheduler} [scheduler] Scheduler used to drain the queue upon completion of the source sequence. + * @returns {Observable} An observable sequence containing the specified number of elements from the end of the source sequence. + */ + observableProto.takeLast = function (count, scheduler) { + return this.takeLastBuffer(count).selectMany(function (xs) { return observableFromArray(xs, scheduler); }); + }; + + /** + * Returns an array with the specified number of contiguous elements from the end of an observable sequence. + * + * @description + * This operator accumulates a buffer with a length enough to store count elements. Upon completion of the + * source sequence, this buffer is produced on the result sequence. + * @param {Number} count Number of elements to take from the end of the source sequence. + * @returns {Observable} An observable sequence containing a single array with the specified number of elements from the end of the source sequence. + */ + observableProto.takeLastBuffer = function (count) { + var source = this; + return new AnonymousObservable(function (observer) { + var q = []; + return source.subscribe(function (x) { + q.push(x); + if (q.length > count) { + q.shift(); + } + }, observer.onError.bind(observer), function () { + observer.onNext(q); + observer.onCompleted(); + }); + }); + }; + + /** + * Projects each element of an observable sequence into zero or more windows which are produced based on element count information. + * + * var res = xs.windowWithCount(10); + * var res = xs.windowWithCount(10, 1); + * @param {Number} count Length of each window. + * @param {Number} [skip] Number of elements to skip between creation of consecutive windows. If not specified, defaults to the count. + * @returns {Observable} An observable sequence of windows. + */ + observableProto.windowWithCount = function (count, skip) { + var source = this; + if (count <= 0) { + throw new Error(argumentOutOfRange); + } + if (arguments.length === 1) { + skip = count; + } + if (skip <= 0) { + throw new Error(argumentOutOfRange); + } + return new AnonymousObservable(function (observer) { + var m = new SingleAssignmentDisposable(), + refCountDisposable = new RefCountDisposable(m), + n = 0, + q = [], + createWindow = function () { + var s = new Subject(); + q.push(s); + observer.onNext(addRef(s, refCountDisposable)); + }; + createWindow(); + m.setDisposable(source.subscribe(function (x) { + var s; + for (var i = 0, len = q.length; i < len; i++) { + q[i].onNext(x); + } + var c = n - count + 1; + if (c >= 0 && c % skip === 0) { + s = q.shift(); + s.onCompleted(); + } + n++; + if (n % skip === 0) { + createWindow(); + } + }, function (exception) { + while (q.length > 0) { + q.shift().onError(exception); + } + observer.onError(exception); + }, function () { + while (q.length > 0) { + q.shift().onCompleted(); + } + observer.onCompleted(); + })); + return refCountDisposable; + }); + }; + + function concatMap(selector) { + return this.map(function (x, i) { + var result = selector(x, i); + return isPromise(result) ? observableFromPromise(result) : result; + }).concatAll(); + } + + function concatMapObserver(onNext, onError, onCompleted) { + var source = this; + return new AnonymousObservable(function (observer) { + var index = 0; + + return source.subscribe( + function (x) { + observer.onNext(onNext(x, index++)); + }, + function (err) { + observer.onNext(onError(err)); + observer.completed(); + }, + function () { + observer.onNext(onCompleted()); + observer.onCompleted(); + }); + }).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.selectMany(function (x) { return Rx.Observable.range(0, x); }); + * Or: + * Projects each element of an observable sequence to an observable sequence, invokes the result selector for the source element and each of the corresponding inner sequence's elements, and merges the results into one observable sequence. + * + * var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); }, function (x, y) { return x + y; }); + * Or: + * Projects each element of the source observable sequence to the other observable sequence and merges the resulting observable sequences into one observable sequence. + * + * var res = source.selectMany(Rx.Observable.fromArray([1,2,3])); + * @param selector A transform function to apply to each element or an observable sequence to project each element from the + * source sequence onto which could be either an observable or Promise. + * @param {Function} [resultSelector] A transform function to apply to each element of the intermediate sequence. + * @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) { + if (resultSelector) { + return this.concatMap(function (x, i) { + var selectorResult = selector(x, i), + result = isPromise(selectorResult) ? observableFromPromise(selectorResult) : selectorResult; + + return result.map(function (y) { + return resultSelector(x, y, i); + }); + }); + } + if (typeof selector === 'function') { + return concatMap.call(this, selector); + } + return concatMap.call(this, function () { + return selector; + }); + }; + + /** + * Returns the elements of the specified sequence or the specified value in a singleton sequence if the sequence is empty. + * + * var res = obs = xs.defaultIfEmpty(); + * 2 - obs = xs.defaultIfEmpty(false); + * + * @memberOf Observable# + * @param defaultValue The value to return if the sequence is empty. If not provided, this defaults to null. + * @returns {Observable} An observable sequence that contains the specified default value if the source is empty; otherwise, the elements of the source itself. + */ + observableProto.defaultIfEmpty = function (defaultValue) { + var source = this; + if (defaultValue === undefined) { + defaultValue = null; + } + return new AnonymousObservable(function (observer) { + var found = false; + return source.subscribe(function (x) { + found = true; + observer.onNext(x); + }, observer.onError.bind(observer), function () { + if (!found) { + observer.onNext(defaultValue); + } + observer.onCompleted(); + }); + }); + }; + + /** + * Returns an observable sequence that contains only distinct elements according to the keySelector and the comparer. + * Usage of this operator should be considered carefully due to the maintenance of an internal lookup structure which can grow large. + * + * @example + * var res = obs = xs.distinct(); + * 2 - obs = xs.distinct(function (x) { return x.id; }); + * 2 - obs = xs.distinct(function (x) { return x.id; }, function (x) { return x.toString(); }); + * @param {Function} [keySelector] A function to compute the comparison key for each element. + * @param {Function} [keySerializer] Used to serialize the given object into a string for object comparison. + * @returns {Observable} An observable sequence only containing the distinct elements, based on a computed key value, from the source sequence. + */ + observableProto.distinct = function (keySelector, keySerializer) { + var source = this; + keySelector || (keySelector = identity); + keySerializer || (keySerializer = defaultKeySerializer); + return new AnonymousObservable(function (observer) { + var hashSet = {}; + return source.subscribe(function (x) { + var key, serializedKey, otherKey, hasMatch = false; + try { + key = keySelector(x); + serializedKey = keySerializer(key); + } catch (exception) { + observer.onError(exception); + return; + } + for (otherKey in hashSet) { + if (serializedKey === otherKey) { + hasMatch = true; + break; + } + } + if (!hasMatch) { + hashSet[serializedKey] = null; + observer.onNext(x); + } + }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); + }); + }; + + /** + * Groups the elements of an observable sequence according to a specified key selector function and comparer and selects the resulting elements by using a specified function. + * + * @example + * var res = observable.groupBy(function (x) { return x.id; }); + * 2 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }); + * 3 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }, function (x) { return x.toString(); }); + * @param {Function} keySelector A function to extract the key for each element. + * @param {Function} [elementSelector] A function to map each source element to an element in an observable group. + * @param {Function} [keySerializer] Used to serialize the given object into a string for object comparison. + * @returns {Observable} A sequence of observable groups, each of which corresponds to a unique key value, containing all elements that share that same key value. + */ + observableProto.groupBy = function (keySelector, elementSelector, keySerializer) { + return this.groupByUntil(keySelector, elementSelector, function () { + return observableNever(); + }, keySerializer); + }; + + /** + * Groups the elements of an observable sequence according to a specified key selector function. + * A duration selector function is used to control the lifetime of groups. When a group expires, it receives an OnCompleted notification. When a new element with the same + * key value as a reclaimed group occurs, the group will be reborn with a new lifetime request. + * + * @example + * var res = observable.groupByUntil(function (x) { return x.id; }, null, function () { return Rx.Observable.never(); }); + * 2 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }, function () { return Rx.Observable.never(); }); + * 3 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }, function () { return Rx.Observable.never(); }, function (x) { return x.toString(); }); + * @param {Function} keySelector A function to extract the key for each element. + * @param {Function} durationSelector A function to signal the expiration of a group. + * @param {Function} [keySerializer] Used to serialize the given object into a string for object comparison. + * @returns {Observable} + * A sequence of observable groups, each of which corresponds to a unique key value, containing all elements that share that same key value. + * If a group's lifetime expires, a new group with the same key value can be created once an element with such a key value is encoutered. + * + */ + observableProto.groupByUntil = function (keySelector, elementSelector, durationSelector, keySerializer) { + var source = this; + elementSelector || (elementSelector = identity); + keySerializer || (keySerializer = defaultKeySerializer); + return new AnonymousObservable(function (observer) { + var map = {}, + groupDisposable = new CompositeDisposable(), + refCountDisposable = new RefCountDisposable(groupDisposable); + groupDisposable.add(source.subscribe(function (x) { + var duration, durationGroup, element, fireNewMapEntry, group, key, serializedKey, md, writer, w; + try { + key = keySelector(x); + serializedKey = keySerializer(key); + } catch (e) { + for (w in map) { + map[w].onError(e); + } + observer.onError(e); + return; + } + fireNewMapEntry = false; + try { + writer = map[serializedKey]; + if (!writer) { + writer = new Subject(); + map[serializedKey] = writer; + fireNewMapEntry = true; + } + } catch (e) { + for (w in map) { + map[w].onError(e); + } + observer.onError(e); + return; + } + if (fireNewMapEntry) { + group = new GroupedObservable(key, writer, refCountDisposable); + durationGroup = new GroupedObservable(key, writer); + try { + duration = durationSelector(durationGroup); + } catch (e) { + for (w in map) { + map[w].onError(e); + } + observer.onError(e); + return; + } + observer.onNext(group); + md = new SingleAssignmentDisposable(); + groupDisposable.add(md); + var expire = function () { + if (serializedKey in map) { + delete map[serializedKey]; + writer.onCompleted(); + } + groupDisposable.remove(md); + }; + md.setDisposable(duration.take(1).subscribe(noop, function (exn) { + for (w in map) { + map[w].onError(exn); + } + observer.onError(exn); + }, function () { + expire(); + })); + } + try { + element = elementSelector(x); + } catch (e) { + for (w in map) { + map[w].onError(e); + } + observer.onError(e); + return; + } + writer.onNext(element); + }, function (ex) { + for (var w in map) { + map[w].onError(ex); + } + observer.onError(ex); + }, function () { + for (var w in map) { + map[w].onCompleted(); + } + observer.onCompleted(); + })); + return refCountDisposable; + }); + }; + + /** + * Projects each element of an observable sequence into a new form by incorporating the element's index. + * @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element. + * @param {Any} [thisArg] Object to use as this when executing callback. + * @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source. + */ + observableProto.select = observableProto.map = function (selector, thisArg) { + var parent = this; + return new AnonymousObservable(function (observer) { + var count = 0; + return parent.subscribe(function (value) { + var result; + try { + result = selector.call(thisArg, value, count++, parent); + } catch (exception) { + observer.onError(exception); + return; + } + observer.onNext(result); + }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); + }); + }; + + /** + * Retrieves the value of a specified property from all elements in the Observable sequence. + * @param {String} property The property to pluck. + * @returns {Observable} Returns a new Observable sequence of property values. + */ + observableProto.pluck = function (property) { + return this.select(function (x) { return x[property]; }); + }; + + function selectMany(selector) { + return this.select(function (x, i) { + var result = selector(x, i); + return isPromise(result) ? observableFromPromise(result) : result; + }).mergeObservable(); + } + + function selectManyObserver(onNext, onError, onCompleted) { + var source = this; + return new AnonymousObservable(function (observer) { + var index = 0; + + return source.subscribe( + function (x) { + observer.onNext(onNext(x, index++)); + }, + function (err) { + observer.onNext(onError(err)); + observer.completed(); + }, + function () { + observer.onNext(onCompleted()); + observer.onCompleted(); + }); + }).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 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.selectMany = observableProto.flatMap = function (selector, resultSelector) { + if (resultSelector) { + return this.selectMany(function (x, i) { + var selectorResult = selector(x, i), + result = isPromise(selectorResult) ? observableFromPromise(selectorResult) : selectorResult; + + return result.select(function (y) { + return resultSelector(x, y, i); + }); + }); + } + if (typeof selector === 'function') { + return selectMany.call(this, selector); + } + return selectMany.call(this, function () { + return selector; + }); + }; + + /** + * Projects each element of an observable sequence into a new sequence of observable sequences by incorporating the element's index and then + * transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence. + * @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element. + * @param {Any} [thisArg] Object to use as this when executing callback. + * @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source producing an Observable of Observable sequences + * and that at any point in time produces the elements of the most recent inner observable sequence that has been received. + */ + observableProto.selectSwitch = observableProto.flatMapLatest = observableProto.switchMap = function (selector, thisArg) { + return this.select(selector, thisArg).switchLatest(); + }; + + /** + * Bypasses a specified number of elements in an observable sequence and then returns the remaining elements. + * @param {Number} count The number of elements to skip before returning the remaining elements. + * @returns {Observable} An observable sequence that contains the elements that occur after the specified index in the input sequence. + */ + observableProto.skip = function (count) { + if (count < 0) { + throw new Error(argumentOutOfRange); + } + var observable = this; + return new AnonymousObservable(function (observer) { + var remaining = count; + return observable.subscribe(function (x) { + if (remaining <= 0) { + observer.onNext(x); + } else { + remaining--; + } + }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); + }); + }; + + /** + * Bypasses elements in an observable sequence as long as a specified condition is true and then returns the remaining elements. + * The element's index is used in the logic of the predicate function. + * + * var res = source.skipWhile(function (value) { return value < 10; }); + * var res = source.skipWhile(function (value, index) { return value < 10 || index < 10; }); + * @param {Function} predicate A function to test each element for a condition; the second parameter of the function represents the index of the source element. + * @param {Any} [thisArg] Object to use as this when executing callback. + * @returns {Observable} An observable sequence that contains the elements from the input sequence starting at the first element in the linear series that does not pass the test specified by predicate. + */ + observableProto.skipWhile = function (predicate, thisArg) { + var source = this; + return new AnonymousObservable(function (observer) { + var i = 0, running = false; + return source.subscribe(function (x) { + if (!running) { + try { + running = !predicate.call(thisArg, x, i++, source); + } catch (e) { + observer.onError(e); + return; + } + } + if (running) { + observer.onNext(x); + } + }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); + }); + }; + + /** + * Returns a specified number of contiguous elements from the start of an observable sequence, using the specified scheduler for the edge case of take(0). + * + * var res = source.take(5); + * var res = source.take(0, Rx.Scheduler.timeout); + * @param {Number} count The number of elements to return. + * @param {Scheduler} [scheduler] Scheduler used to produce an OnCompleted message in case ++c;)o=te[c],l&&l[o]||!K.call(t,o)||e.push(o)}return e}function i(t,e,n){for(var r=-1,i=n(t),o=i.length;o>++r;){var s=i[r];if(e(t[s],s,t)===!1)break}return t}function o(t,e){return i(t,e,r)}function s(t){return"function"!=typeof t.toString&&"string"==typeof(t+"")}function u(t){return t&&"object"==typeof t?$.call(t)==V:!1}function c(t){return"function"==typeof t||!1}function a(e,n,r,i){if(e===n)return 0!==e||1/e==1/n;var h=typeof e,l=typeof n;if(e===e&&(null==e||null==n||"function"!=h&&"object"!=h&&"function"!=l&&"object"!=l))return!1;var f=$.call(e),p=$.call(n);if(f==V&&(f=H),p==V&&(p=H),f!=p)return!1;switch(f){case z:case M:return+e==+n;case B:return e!=+e?n!=+n:0==e?1/e==1/n:e==+n;case U:case Q:return e==n+""}var d=f==L;if(!d){if(f!=H||!ne.nodeClass&&(s(e)||s(n)))return!1;var v=!ne.argsObject&&u(e)?Object:e.constructor,b=!ne.argsObject&&u(n)?Object:n.constructor;if(!(v==b||K.call(e,"constructor")&&K.call(n,"constructor")||c(v)&&v instanceof v&&c(b)&&b instanceof b||!("constructor"in e&&"constructor"in n)))return!1}r||(r=[]),i||(i=[]);for(var m=r.length;m--;)if(r[m]==e)return i[m]==n;var y=0;if(result=!0,r.push(e),i.push(n),d){if(m=e.length,y=n.length,result=y==m)for(;y--;){var w=n[y];if(!(result=a(e[y],w,r,i)))break}}else o(n,function(n,o,s){return K.call(s,o)?(y++,result=K.call(e,o)&&a(e[o],n,r,i)):t}),result&&o(e,function(e,n,r){return K.call(r,n)?result=--y>-1:t});return r.pop(),i.pop(),result}function h(t,e){return 1===t.length&&Array.isArray(t[e])?t[e]:ie.call(t)}function l(t,e){for(var n=Array(t),r=0;t>r;r++)n[r]=e();return n}function f(t,e){this.scheduler=t,this.disposable=e,this.isDisposed=!1}function p(e,n){return new on(function(r){var i=new we,o=new ge;return o.setDisposable(i),i.setDisposable(e.subscribe(r.onNext.bind(r),function(e){var i,s;try{s=n(e)}catch(u){return r.onError(u),t}j(s)&&(s=$e(s)),i=new we,o.setDisposable(i),i.setDisposable(s.subscribe(r))},r.onCompleted.bind(r))),o})}function d(e,n){var r=this;return new on(function(i){var o=0,s=e.length;return r.subscribe(function(r){if(s>o){var u,c=e[o++];try{u=n(r,c)}catch(a){return i.onError(a),t}i.onNext(u)}else i.onCompleted()},i.onError.bind(i),i.onCompleted.bind(i))})}function v(t){return this.map(function(e,n){var r=t(e,n);return j(r)?$e(r):r}).concatAll()}function b(t){return this.select(function(e,n){var r=t(e,n);return j(r)?$e(r):r}).mergeObservable()}var m={"boolean":!1,"function":!0,object:!0,number:!1,string:!1,undefined:!1},y=m[typeof window]&&window||this,w=m[typeof exports]&&exports&&!exports.nodeType&&exports,g=m[typeof module]&&module&&!module.nodeType&&module,E=g&&g.exports===w&&w,x=m[typeof global]&&global;!x||x.global!==x&&x.window!==x||(y=x);var C={internals:{},config:{Promise:y.Promise},helpers:{}},D=C.helpers.noop=function(){},S=C.helpers.identity=function(t){return t},A=(C.helpers.pluck=function(t){return function(e){return e[t]}},C.helpers.just=function(t){return function(){return t}},C.helpers.defaultNow=function(){return Date.now?Date.now:function(){return+new Date}}()),N=C.helpers.defaultComparer=function(t,e){return re(t,e)},_=C.helpers.defaultSubComparer=function(t,e){return t>e?1:e>t?-1:0},O=C.helpers.defaultKeySerializer=function(t){return""+t},W=C.helpers.defaultError=function(t){throw t},j=C.helpers.isPromise=function(t){return!!t&&"function"==typeof t.then&&t.then!==C.Observable.prototype.then};C.helpers.asArray=function(){return Array.prototype.slice.call(arguments)},C.helpers.not=function(t){return!t};var R="Argument out of range",k="Object has been disposed",q="object"==typeof Symbol&&Symbol.iterator||"_es6shim_iterator_";y.Set&&"function"==typeof(new y.Set)["@@iterator"]&&(q="@@iterator");var P,T={done:!0,value:t},V="[object Arguments]",L="[object Array]",z="[object Boolean]",M="[object Date]",I="[object Error]",F="[object Function]",B="[object Number]",H="[object Object]",U="[object RegExp]",Q="[object String]",$=Object.prototype.toString,K=Object.prototype.hasOwnProperty,J=$.call(arguments)==V,X=Error.prototype,Z=Object.prototype,G=Z.propertyIsEnumerable;try{P=!($.call(document)==H&&!({toString:0}+""))}catch(Y){P=!0}var te=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],ee={};ee[L]=ee[M]=ee[B]={constructor:!0,toLocaleString:!0,toString:!0,valueOf:!0},ee[z]=ee[Q]={constructor:!0,toString:!0,valueOf:!0},ee[I]=ee[F]=ee[U]={constructor:!0,toString:!0},ee[H]={constructor:!0};var ne={};(function(){var t=function(){this.x=1},e=[];t.prototype={valueOf:1,y:1};for(var n in new t)e.push(n);for(n in arguments);ne.enumErrorProps=G.call(X,"message")||G.call(X,"name"),ne.enumPrototypes=G.call(t,"prototype"),ne.nonEnumArgs=0!=n,ne.nonEnumShadows=!/valueOf/.test(e)})(1),J||(u=function(t){return t&&"object"==typeof t?K.call(t,"callee"):!1}),c(/x/)&&(c=function(t){return"function"==typeof t&&$.call(t)==F});var re=C.internals.isEqual=function(t,e){return a(t,e,[],[])},ie=Array.prototype.slice;({}).hasOwnProperty;var oe=this.inherits=C.internals.inherits=function(t,e){function n(){this.constructor=t}n.prototype=e.prototype,t.prototype=new n},se=C.internals.addProperties=function(t){for(var e=ie.call(arguments,1),n=0,r=e.length;r>n;n++){var i=e[n];for(var o in i)t[o]=i[o]}},ue=C.internals.addRef=function(t,e){return new on(function(n){return new pe(e.getDisposable(),t.subscribe(n))})};Function.prototype.bind||(Function.prototype.bind=function(t){var e=this,n=ie.call(arguments,1),r=function(){function i(){}if(this instanceof r){i.prototype=e.prototype;var o=new i,s=e.apply(o,n.concat(ie.call(arguments)));return Object(s)===s?s:o}return e.apply(t,n.concat(ie.call(arguments)))};return r});var ce=Object("a"),ae="a"!=ce[0]||!(0 in ce);Array.prototype.every||(Array.prototype.every=function(t){var e=Object(this),n=ae&&{}.toString.call(this)==Q?this.split(""):e,r=n.length>>>0,i=arguments[1];if({}.toString.call(t)!=F)throw new TypeError(t+" is not a function");for(var o=0;r>o;o++)if(o in n&&!t.call(i,n[o],o,e))return!1;return!0}),Array.prototype.map||(Array.prototype.map=function(t){var e=Object(this),n=ae&&{}.toString.call(this)==Q?this.split(""):e,r=n.length>>>0,i=Array(r),o=arguments[1];if({}.toString.call(t)!=F)throw new TypeError(t+" is not a function");for(var s=0;r>s;s++)s in n&&(i[s]=t.call(o,n[s],s,e));return i}),Array.prototype.filter||(Array.prototype.filter=function(t){for(var e,n=[],r=Object(this),i=0,o=r.length>>>0;o>i;i++)e=r[i],i in r&&t.call(arguments[1],e,i,r)&&n.push(e);return n}),Array.isArray||(Array.isArray=function(t){return Object.prototype.toString.call(t)==L}),Array.prototype.indexOf||(Array.prototype.indexOf=function(t){var e=Object(this),n=e.length>>>0;if(0===n)return-1;var r=0;if(arguments.length>1&&(r=Number(arguments[1]),r!==r?r=0:0!==r&&1/0!=r&&r!==-1/0&&(r=(r>0||-1)*Math.floor(Math.abs(r)))),r>=n)return-1;for(var i=r>=0?r:Math.max(n-Math.abs(r),0);n>i;i++)if(i in e&&e[i]===t)return i;return-1});var he=function(t,e){this.id=t,this.value=e};he.prototype.compareTo=function(t){var e=this.value.compareTo(t.value);return 0===e&&(e=this.id-t.id),e};var le=C.internals.PriorityQueue=function(t){this.items=Array(t),this.length=0},fe=le.prototype;fe.isHigherPriority=function(t,e){return 0>this.items[t].compareTo(this.items[e])},fe.percolate=function(t){if(!(t>=this.length||0>t)){var e=t-1>>1;if(!(0>e||e===t)&&this.isHigherPriority(t,e)){var n=this.items[t];this.items[t]=this.items[e],this.items[e]=n,this.percolate(e)}}},fe.heapify=function(e){if(e===t&&(e=0),!(e>=this.length||0>e)){var n=2*e+1,r=2*e+2,i=e;if(this.length>n&&this.isHigherPriority(n,i)&&(i=n),this.length>r&&this.isHigherPriority(r,i)&&(i=r),i!==e){var o=this.items[e];this.items[e]=this.items[i],this.items[i]=o,this.heapify(i)}}},fe.peek=function(){return this.items[0].value},fe.removeAt=function(t){this.items[t]=this.items[--this.length],delete this.items[this.length],this.heapify()},fe.dequeue=function(){var t=this.peek();return this.removeAt(0),t},fe.enqueue=function(t){var e=this.length++;this.items[e]=new he(le.count++,t),this.percolate(e)},fe.remove=function(t){for(var e=0;this.length>e;e++)if(this.items[e].value===t)return this.removeAt(e),!0;return!1},le.count=0;var pe=C.CompositeDisposable=function(){this.disposables=h(arguments,0),this.isDisposed=!1,this.length=this.disposables.length},de=pe.prototype;de.add=function(t){this.isDisposed?t.dispose():(this.disposables.push(t),this.length++)},de.remove=function(t){var e=!1;if(!this.isDisposed){var n=this.disposables.indexOf(t);-1!==n&&(e=!0,this.disposables.splice(n,1),this.length--,t.dispose())}return e},de.dispose=function(){if(!this.isDisposed){this.isDisposed=!0;var t=this.disposables.slice(0);this.disposables=[],this.length=0;for(var e=0,n=t.length;n>e;e++)t[e].dispose()}},de.clear=function(){var t=this.disposables.slice(0);this.disposables=[],this.length=0;for(var e=0,n=t.length;n>e;e++)t[e].dispose()},de.contains=function(t){return-1!==this.disposables.indexOf(t)},de.toArray=function(){return this.disposables.slice(0)};var ve=C.Disposable=function(t){this.isDisposed=!1,this.action=t||D};ve.prototype.dispose=function(){this.isDisposed||(this.action(),this.isDisposed=!0)};var be=ve.create=function(t){return new ve(t)},me=ve.empty={dispose:D},ye=function(){function t(t){this.isSingle=t,this.isDisposed=!1,this.current=null}var e=t.prototype;return e.getDisposable=function(){return this.current},e.setDisposable=function(t){if(this.current&&this.isSingle)throw Error("Disposable has already been assigned");var e,n=this.isDisposed;n||(e=this.current,this.current=t),e&&e.dispose(),n&&t&&t.dispose()},e.dispose=function(){var t;this.isDisposed||(this.isDisposed=!0,t=this.current,this.current=null),t&&t.dispose()},t}(),we=C.SingleAssignmentDisposable=function(t){function e(){t.call(this,!0)}return oe(e,t),e}(ye),ge=C.SerialDisposable=function(t){function e(){t.call(this,!1)}return oe(e,t),e}(ye),Ee=C.RefCountDisposable=function(){function t(t){this.disposable=t,this.disposable.count++,this.isInnerDisposed=!1}function e(t){this.underlyingDisposable=t,this.isDisposed=!1,this.isPrimaryDisposed=!1,this.count=0}return t.prototype.dispose=function(){this.disposable.isDisposed||this.isInnerDisposed||(this.isInnerDisposed=!0,this.disposable.count--,0===this.disposable.count&&this.disposable.isPrimaryDisposed&&(this.disposable.isDisposed=!0,this.disposable.underlyingDisposable.dispose()))},e.prototype.dispose=function(){this.isDisposed||this.isPrimaryDisposed||(this.isPrimaryDisposed=!0,0===this.count&&(this.isDisposed=!0,this.underlyingDisposable.dispose()))},e.prototype.getDisposable=function(){return this.isDisposed?me:new t(this)},e}();f.prototype.dispose=function(){var t=this;this.scheduler.schedule(function(){t.isDisposed||(t.isDisposed=!0,t.disposable.dispose())})};var xe=C.internals.ScheduledItem=function(t,e,n,r,i){this.scheduler=t,this.state=e,this.action=n,this.dueTime=r,this.comparer=i||_,this.disposable=new we};xe.prototype.invoke=function(){this.disposable.setDisposable(this.invokeCore())},xe.prototype.compareTo=function(t){return this.comparer(this.dueTime,t.dueTime)},xe.prototype.isCancelled=function(){return this.disposable.isDisposed},xe.prototype.invokeCore=function(){return this.action(this.scheduler,this.state)};var Ce=C.Scheduler=function(){function t(t,e,n,r){this.now=t,this._schedule=e,this._scheduleRelative=n,this._scheduleAbsolute=r}function e(t,e){var n=e.first,r=e.second,i=new pe,o=function(e){r(e,function(e){var n=!1,r=!1,s=t.scheduleWithState(e,function(t,e){return n?i.remove(s):r=!0,o(e),me});r||(i.add(s),n=!0)})};return o(n),i}function n(t,e,n){var r=e.first,i=e.second,o=new pe,s=function(e){i(e,function(e,r){var i=!1,u=!1,c=t[n].call(t,e,r,function(t,e){return i?o.remove(c):u=!0,s(e),me});u||(o.add(c),i=!0)})};return s(r),o}function r(t,e){return e(),me}var i=t.prototype;return i.catchException=i["catch"]=function(t){return new Oe(this,t)},i.schedulePeriodic=function(t,e){return this.schedulePeriodicWithState(null,t,function(){e()})},i.schedulePeriodicWithState=function(t,e,n){var r=t,i=setInterval(function(){r=n(r)},e);return be(function(){clearInterval(i)})},i.schedule=function(t){return this._schedule(t,r)},i.scheduleWithState=function(t,e){return this._schedule(t,e)},i.scheduleWithRelative=function(t,e){return this._scheduleRelative(e,t,r)},i.scheduleWithRelativeAndState=function(t,e,n){return this._scheduleRelative(t,e,n)},i.scheduleWithAbsolute=function(t,e){return this._scheduleAbsolute(e,t,r)},i.scheduleWithAbsoluteAndState=function(t,e,n){return this._scheduleAbsolute(t,e,n)},i.scheduleRecursive=function(t){return this.scheduleRecursiveWithState(t,function(t,e){t(function(){e(t)})})},i.scheduleRecursiveWithState=function(t,n){return this.scheduleWithState({first:t,second:n},function(t,n){return e(t,n)})},i.scheduleRecursiveWithRelative=function(t,e){return this.scheduleRecursiveWithRelativeAndState(e,t,function(t,e){t(function(n){e(t,n)})})},i.scheduleRecursiveWithRelativeAndState=function(t,e,r){return this._scheduleRelative({first:t,second:r},e,function(t,e){return n(t,e,"scheduleWithRelativeAndState")})},i.scheduleRecursiveWithAbsolute=function(t,e){return this.scheduleRecursiveWithAbsoluteAndState(e,t,function(t,e){t(function(n){e(t,n)})})},i.scheduleRecursiveWithAbsoluteAndState=function(t,e,r){return this._scheduleAbsolute({first:t,second:r},e,function(t,e){return n(t,e,"scheduleWithAbsoluteAndState")})},t.now=A,t.normalize=function(t){return 0>t&&(t=0),t},t}(),De=Ce.normalize;C.internals.SchedulePeriodicRecursive=function(){function t(t,e){e(0,this._period);try{this._state=this._action(this._state)}catch(n){throw this._cancel.dispose(),n}}function e(t,e,n,r){this._scheduler=t,this._state=e,this._period=n,this._action=r}return e.prototype.start=function(){var e=new we;return this._cancel=e,e.setDisposable(this._scheduler.scheduleRecursiveWithRelativeAndState(0,this._period,t.bind(this))),e},e}();var Se,Ae=Ce.immediate=function(){function t(t,e){return e(this,t)}function e(t,e,n){for(var r=De(r);r-this.now()>0;);return n(this,t)}function n(t,e,n){return this.scheduleWithRelativeAndState(t,e-this.now(),n)}return new Ce(A,t,e,n)}(),Ne=Ce.currentThread=function(){function t(t){for(var e;t.length>0;)if(e=t.dequeue(),!e.isCancelled()){for(;e.dueTime-Ce.now()>0;);e.isCancelled()||e.invoke()}}function e(t,e){return this.scheduleWithRelativeAndState(t,0,e)}function n(e,n,r){var o=this.now()+Ce.normalize(n),s=new xe(this,e,r,o);if(i)i.enqueue(s);else{i=new le(4),i.enqueue(s);try{t(i)}catch(u){throw u}finally{i=null}}return s.disposable}function r(t,e,n){return this.scheduleWithRelativeAndState(t,e-this.now(),n)}var i,o=new Ce(A,e,n,r);return o.scheduleRequired=function(){return null===i},o.ensureTrampoline=function(t){return null===i?this.schedule(t):t()},o}(),_e=D;(function(){function t(){if(!y.postMessage||y.importScripts)return!1;var t=!1,e=y.onmessage;return y.onmessage=function(){t=!0},y.postMessage("","*"),y.onmessage=e,t}function e(t){if("string"==typeof t.data&&t.data.substring(0,o.length)===o){var e=t.data.substring(o.length),n=s[e];n(),delete s[e]}}var n=RegExp("^"+($+"").replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/toString| for [^\]]+/g,".*?")+"$"),r="function"==typeof(r=x&&E&&x.setImmediate)&&!n.test(r)&&r,i="function"==typeof(i=x&&E&&x.clearImmediate)&&!n.test(i)&&i;if("undefined"!=typeof process&&"[object process]"==={}.toString.call(process))Se=process.nextTick;else if("function"==typeof r)Se=r,_e=i;else if(t()){var o="ms.rx.schedule"+Math.random(),s={},u=0;y.addEventListener?y.addEventListener("message",e,!1):y.attachEvent("onmessage",e,!1),Se=function(t){var e=u++;s[e]=t,y.postMessage(o+e,"*")}}else if(y.MessageChannel){var c=new y.MessageChannel,a={},h=0;c.port1.onmessage=function(t){var e=t.data,n=a[e];n(),delete a[e]},Se=function(t){var e=h++;a[e]=t,c.port2.postMessage(e)}}else"document"in y&&"onreadystatechange"in y.document.createElement("script")?Se=function(t){var e=y.document.createElement("script");e.onreadystatechange=function(){t(),e.onreadystatechange=null,e.parentNode.removeChild(e),e=null},y.document.documentElement.appendChild(e)}:(Se=function(t){return setTimeout(t,0)},_e=clearTimeout)})(),Ce.timeout=function(){function t(t,e){var n=this,r=new we,i=Se(function(){r.isDisposed||r.setDisposable(e(n,t))});return new pe(r,be(function(){_e(i)}))}function e(t,e,n){var r=this,i=Ce.normalize(e);if(0===i)return r.scheduleWithState(t,n);var o=new we,s=setTimeout(function(){o.isDisposed||o.setDisposable(n(r,t))},i);return new pe(o,be(function(){clearTimeout(s)}))}function n(t,e,n){return this.scheduleWithRelativeAndState(t,e-this.now(),n)}return new Ce(A,t,e,n)}();var Oe=function(t){function e(){return this._scheduler.now()}function n(t,e){return this._scheduler.scheduleWithState(t,this._wrap(e))}function r(t,e,n){return this._scheduler.scheduleWithRelativeAndState(t,e,this._wrap(n))}function i(t,e,n){return this._scheduler.scheduleWithAbsoluteAndState(t,e,this._wrap(n))}function o(o,s){this._scheduler=o,this._handler=s,this._recursiveOriginal=null,this._recursiveWrapper=null,t.call(this,e,n,r,i)}return oe(o,t),o.prototype._clone=function(t){return new o(t,this._handler)},o.prototype._wrap=function(t){var e=this;return function(n,r){try{return t(e._getRecursiveWrapper(n),r)}catch(i){if(!e._handler(i))throw i;return me}}},o.prototype._getRecursiveWrapper=function(t){if(this._recursiveOriginal!==t){this._recursiveOriginal=t;var e=this._clone(t);e._recursiveOriginal=t,e._recursiveWrapper=e,this._recursiveWrapper=e}return this._recursiveWrapper},o.prototype.schedulePeriodicWithState=function(t,e,n){var r=this,i=!1,o=new we;return o.setDisposable(this._scheduler.schedulePeriodicWithState(t,e,function(t){if(i)return null;try{return n(t)}catch(e){if(i=!0,!r._handler(e))throw e;return o.dispose(),null}})),o},o}(Ce),We=C.Notification=function(){function t(t,e){this.hasValue=null==e?!1:e,this.kind=t}var e=t.prototype;return e.accept=function(t,e,n){return 1===arguments.length&&"object"==typeof t?this._acceptObservable(t):this._accept(t,e,n)},e.toObservable=function(t){var e=this;return t||(t=Ae),new on(function(n){return t.schedule(function(){e._acceptObservable(n),"N"===e.kind&&n.onCompleted()})})},t}(),je=We.createOnNext=function(){function t(t){return t(this.value)}function e(t){return t.onNext(this.value)}function n(){return"OnNext("+this.value+")"}return function(r){var i=new We("N",!0);return i.value=r,i._accept=t,i._acceptObservable=e,i.toString=n,i}}(),Re=We.createOnError=function(){function t(t,e){return e(this.exception)}function e(t){return t.onError(this.exception)}function n(){return"OnError("+this.exception+")"}return function(r){var i=new We("E");return i.exception=r,i._accept=t,i._acceptObservable=e,i.toString=n,i}}(),ke=We.createOnCompleted=function(){function t(t,e,n){return n()}function e(t){return t.onCompleted()}function n(){return"OnCompleted()"}return function(){var r=new We("C");return r._accept=t,r._acceptObservable=e,r.toString=n,r}}(),qe=C.internals.Enumerator=function(t){this._next=t};qe.prototype.next=function(){return this._next()},qe.prototype[q]=function(){return this};var Pe=C.internals.Enumerable=function(t){this._iterator=t};Pe.prototype[q]=function(){return this._iterator()},Pe.prototype.concat=function(){var e=this;return new on(function(n){var r;try{r=e[q]()}catch(i){return n.onError(),t}var o,s=new ge,u=Ae.scheduleRecursive(function(e){var i;if(!o){try{i=r.next()}catch(u){return n.onError(u),t}if(i.done)return n.onCompleted(),t;var c=i.value;j(c)&&(c=$e(c));var a=new we;s.setDisposable(a),a.setDisposable(c.subscribe(n.onNext.bind(n),n.onError.bind(n),function(){e()}))}});return new pe(s,u,be(function(){o=!0}))})},Pe.prototype.catchException=function(){var e=this;return new on(function(n){var r;try{r=e[q]()}catch(i){return n.onError(),t}var o,s,u=new ge,c=Ae.scheduleRecursive(function(e){if(!o){var i;try{i=r.next()}catch(c){return n.onError(c),t}if(i.done)return s?n.onError(s):n.onCompleted(),t;var a=i.value;j(a)&&(a=$e(a));var h=new we;u.setDisposable(h),h.setDisposable(a.subscribe(n.onNext.bind(n),function(t){s=t,e()},n.onCompleted.bind(n)))}});return new pe(u,c,be(function(){o=!0}))})};var Te=Pe.repeat=function(t,e){return null==e&&(e=-1),new Pe(function(){var n=e;return new qe(function(){return 0===n?T:(n>0&&n--,{done:!1,value:t})})})},Ve=Pe.forEach=function(t,e,n){return e||(e=S),new Pe(function(){var r=-1;return new qe(function(){return++r0&&(e=!this.isAcquired,this.isAcquired=!0),e&&this.disposable.setDisposable(this.scheduler.scheduleRecursive(function(e){var r;if(!(n.queue.length>0))return n.isAcquired=!1,t;r=n.queue.shift();try{r()}catch(i){throw n.queue=[],n.hasFaulted=!0,i}e()}))},n.prototype.dispose=function(){e.prototype.dispose.call(this),this.disposable.dispose()},n}(Ie),Ue=function(t){function e(){t.apply(this,arguments)}return oe(e,t),e.prototype.next=function(e){t.prototype.next.call(this,e),this.ensureActive()},e.prototype.error=function(e){t.prototype.error.call(this,e),this.ensureActive()},e.prototype.completed=function(){t.prototype.completed.call(this),this.ensureActive()},e}(He),Qe=C.Observable=function(){function t(t){this._subscribe=t}return Me=t.prototype,Me.subscribe=Me.forEach=function(t,e,n){var r="object"==typeof t?t:ze(t,e,n);return this._subscribe(r)},t}();Me.observeOn=function(t){var e=this;return new on(function(n){return e.subscribe(new Ue(t,n))})},Me.subscribeOn=function(t){var e=this;return new on(function(n){var r=new we,i=new ge;return i.setDisposable(r),r.setDisposable(t.schedule(function(){i.setDisposable(new f(t,e.subscribe(n)))})),i})};var $e=Qe.fromPromise=function(t){return new on(function(e){return t.then(function(t){e.onNext(t),e.onCompleted()},function(t){e.onError(t)}),function(){t&&t.abort&&t.abort()}})};Me.toPromise=function(t){if(t||(t=C.config.Promise),!t)throw Error("Promise type not provided nor in Rx.config.Promise");var e=this;return new t(function(t,n){var r,i=!1;e.subscribe(function(t){r=t,i=!0},function(t){n(t)},function(){i&&t(r)})})},Me.toArray=function(){var t=this;return new on(function(e){var n=[];return t.subscribe(n.push.bind(n),e.onError.bind(e),function(){e.onNext(n),e.onCompleted()})})},Qe.create=Qe.createWithDisposable=function(t){return new on(t)},Qe.defer=function(t){return new on(function(e){var n;try{n=t()}catch(r){return Ge(r).subscribe(e)}return j(n)&&(n=$e(n)),n.subscribe(e)})};var Ke=Qe.empty=function(t){return t||(t=Ae),new on(function(e){return t.schedule(function(){e.onCompleted()})})},Je=Qe.fromArray=function(t,e){return e||(e=Ne),new on(function(n){var r=0,i=t.length;return e.scheduleRecursive(function(e){i>r?(n.onNext(t[r++]),e()):n.onCompleted()})})};Qe.fromIterable=function(e,n){return n||(n=Ne),new on(function(r){var i;try{i=e[q]()}catch(o){return r.onError(o),t}return n.scheduleRecursive(function(e){var n;try{n=i.next()}catch(o){return r.onError(o),t}n.done?r.onCompleted():(r.onNext(n.value),e())})})},Qe.generate=function(e,n,r,i,o){return o||(o=Ne),new on(function(s){var u=!0,c=e;return o.scheduleRecursive(function(e){var o,a;try{u?u=!1:c=r(c),o=n(c),o&&(a=i(c))}catch(h){return s.onError(h),t}o?(s.onNext(a),e()):s.onCompleted()})})};var Xe=Qe.never=function(){return new on(function(){return me})};Qe.of=function(){for(var t=arguments.length,e=Array(t),n=0;t>n;n++)e[n]=arguments[n];return Je(e)},Qe.ofWithScheduler=function(t){for(var e=arguments.length-1,n=Array(e),r=0;e>r;r++)n[r]=arguments[r+1];return Je(n,t)},Qe.range=function(t,e,n){return n||(n=Ne),new on(function(r){return n.scheduleRecursiveWithState(0,function(n,i){e>n?(r.onNext(t+n),i(n+1)):r.onCompleted()})})},Qe.repeat=function(t,e,n){return n||(n=Ne),null==e&&(e=-1),Ze(t,n).repeat(e)};var Ze=Qe["return"]=Qe.returnValue=Qe.just=function(t,e){return e||(e=Ae),new on(function(n){return e.schedule(function(){n.onNext(t),n.onCompleted()})})},Ge=Qe["throw"]=Qe.throwException=function(t,e){return e||(e=Ae),new on(function(n){return e.schedule(function(){n.onError(t)})})};Qe.using=function(t,e){return new on(function(n){var r,i,o=me;try{r=t(),r&&(o=r),i=e(r)}catch(s){return new pe(Ge(s).subscribe(n),o)}return new pe(i.subscribe(n),o)})},Me.amb=function(t){var e=this;return new on(function(n){function r(){o||(o=s,a.dispose())}function i(){o||(o=u,c.dispose())}var o,s="L",u="R",c=new we,a=new we;return j(t)&&(t=$e(t)),c.setDisposable(e.subscribe(function(t){r(),o===s&&n.onNext(t)},function(t){r(),o===s&&n.onError(t)},function(){r(),o===s&&n.onCompleted()})),a.setDisposable(t.subscribe(function(t){i(),o===u&&n.onNext(t)},function(t){i(),o===u&&n.onError(t)},function(){i(),o===u&&n.onCompleted()})),new pe(c,a)})},Qe.amb=function(){function t(t,e){return t.amb(e)}for(var e=Xe(),n=h(arguments,0),r=0,i=n.length;i>r;r++)e=t(e,n[r]);return e},Me["catch"]=Me.catchException=function(t){return"function"==typeof t?p(this,t):Ye([this,t])};var Ye=Qe.catchException=Qe["catch"]=function(){var t=h(arguments,0);return Ve(t).catchException()};Me.combineLatest=function(){var t=ie.call(arguments);return Array.isArray(t[0])?t[0].unshift(this):t.unshift(this),tn.apply(this,t)};var tn=Qe.combineLatest=function(){var e=ie.call(arguments),n=e.pop();return Array.isArray(e[0])&&(e=e[0]),new on(function(r){function i(e){var i;if(c[e]=!0,a||(a=c.every(S))){try{i=n.apply(null,f)}catch(o){return r.onError(o),t}r.onNext(i)}else h.filter(function(t,n){return n!==e}).every(S)&&r.onCompleted()}function o(t){h[t]=!0,h.every(S)&&r.onCompleted()}for(var s=function(){return!1},u=e.length,c=l(u,s),a=!1,h=l(u,s),f=Array(u),p=Array(u),d=0;u>d;d++)(function(t){var n=e[t],s=new we;j(n)&&(n=$e(n)),s.setDisposable(n.subscribe(function(e){f[t]=e,i(t)},r.onError.bind(r),function(){o(t)})),p[t]=s})(d);return new pe(p)})};Me.concat=function(){var t=ie.call(arguments,0);return t.unshift(this),en.apply(this,t)};var en=Qe.concat=function(){var t=h(arguments,0);return Ve(t).concat()};Me.concatObservable=Me.concatAll=function(){return this.merge(1)},Me.merge=function(t){if("number"!=typeof t)return nn(this,t);var e=this;return new on(function(n){var r=0,i=new pe,o=!1,s=[],u=function(t){var e=new we;i.add(e),j(t)&&(t=$e(t)),e.setDisposable(t.subscribe(n.onNext.bind(n),n.onError.bind(n),function(){var t;i.remove(e),s.length>0?(t=s.shift(),u(t)):(r--,o&&0===r&&n.onCompleted())}))};return i.add(e.subscribe(function(e){t>r?(r++,u(e)):s.push(e)},n.onError.bind(n),function(){o=!0,0===r&&n.onCompleted()})),i})};var nn=Qe.merge=function(){var t,e;return arguments[0]?arguments[0].now?(t=arguments[0],e=ie.call(arguments,1)):(t=Ae,e=ie.call(arguments,0)):(t=Ae,e=ie.call(arguments,1)),Array.isArray(e[0])&&(e=e[0]),Je(e,t).mergeObservable()};Me.mergeObservable=Me.mergeAll=function(){var t=this;return new on(function(e){var n=new pe,r=!1,i=new we;return n.add(i),i.setDisposable(t.subscribe(function(t){var i=new we;n.add(i),j(t)&&(t=$e(t)),i.setDisposable(t.subscribe(function(t){e.onNext(t)},e.onError.bind(e),function(){n.remove(i),r&&1===n.length&&e.onCompleted()}))},e.onError.bind(e),function(){r=!0,1===n.length&&e.onCompleted()})),n})},Me.onErrorResumeNext=function(t){if(!t)throw Error("Second observable is required");return rn([this,t])};var rn=Qe.onErrorResumeNext=function(){var t=h(arguments,0);return new on(function(e){var n=0,r=new ge,i=Ae.scheduleRecursive(function(i){var o,s;t.length>n?(o=t[n++],j(o)&&(o=$e(o)),s=new we,r.setDisposable(s),s.setDisposable(o.subscribe(e.onNext.bind(e),function(){i()},function(){i()}))):e.onCompleted()});return new pe(r,i)})};Me.skipUntil=function(t){var e=this;return new on(function(n){var r=!1,i=new pe(e.subscribe(function(t){r&&n.onNext(t)},n.onError.bind(n),function(){r&&n.onCompleted()}));j(t)&&(t=$e(t));var o=new we;return i.add(o),o.setDisposable(t.subscribe(function(){r=!0,o.dispose()},n.onError.bind(n),function(){o.dispose()})),i})},Me["switch"]=Me.switchLatest=function(){var t=this;return new on(function(e){var n=!1,r=new ge,i=!1,o=0,s=t.subscribe(function(t){var s=new we,u=++o;n=!0,r.setDisposable(s),j(t)&&(t=$e(t)),s.setDisposable(t.subscribe(function(t){o===u&&e.onNext(t)},function(t){o===u&&e.onError(t)},function(){o===u&&(n=!1,i&&e.onCompleted())}))},e.onError.bind(e),function(){i=!0,n||e.onCompleted()});return new pe(s,r)})},Me.takeUntil=function(t){var e=this;return new on(function(n){return j(t)&&(t=$e(t)),new pe(e.subscribe(n),t.subscribe(n.onCompleted.bind(n),n.onError.bind(n),D))})},Me.zip=function(){if(Array.isArray(arguments[0]))return d.apply(this,arguments);var e=this,n=ie.call(arguments),r=n.pop();return n.unshift(e),new on(function(i){function o(n){var o,s;if(c.every(function(t){return t.length>0})){try{s=c.map(function(t){return t.shift()}),o=r.apply(e,s)}catch(u){return i.onError(u),t}i.onNext(o)}else a.filter(function(t,e){return e!==n}).every(S)&&i.onCompleted()}function s(t){a[t]=!0,a.every(function(t){return t})&&i.onCompleted()}for(var u=n.length,c=l(u,function(){return[]}),a=l(u,function(){return!1}),h=Array(u),f=0;u>f;f++)(function(t){var e=n[t],r=new we; +j(e)&&(e=$e(e)),r.setDisposable(e.subscribe(function(e){c[t].push(e),o(t)},i.onError.bind(i),function(){s(t)})),h[t]=r})(f);return new pe(h)})},Qe.zip=function(){var t=ie.call(arguments,0),e=t.shift();return e.zip.apply(e,t)},Qe.zipArray=function(){var e=h(arguments,0);return new on(function(n){function r(e){if(s.every(function(t){return t.length>0})){var r=s.map(function(t){return t.shift()});n.onNext(r)}else if(u.filter(function(t,n){return n!==e}).every(S))return n.onCompleted(),t}function i(e){return u[e]=!0,u.every(S)?(n.onCompleted(),t):t}for(var o=e.length,s=l(o,function(){return[]}),u=l(o,function(){return!1}),c=Array(o),a=0;o>a;a++)(function(t){c[t]=new we,c[t].setDisposable(e[t].subscribe(function(e){s[t].push(e),r(t)},n.onError.bind(n),function(){i(t)}))})(a);var h=new pe(c);return h.add(be(function(){for(var t=0,e=s.length;e>t;t++)s[t]=[]})),h})},Me.asObservable=function(){var t=this;return new on(function(e){return t.subscribe(e)})},Me.bufferWithCount=function(t,e){return"number"!=typeof e&&(e=t),this.windowWithCount(t,e).selectMany(function(t){return t.toArray()}).where(function(t){return t.length>0})},Me.dematerialize=function(){var t=this;return new on(function(e){return t.subscribe(function(t){return t.accept(e)},e.onError.bind(e),e.onCompleted.bind(e))})},Me.distinctUntilChanged=function(e,n){var r=this;return e||(e=S),n||(n=N),new on(function(i){var o,s=!1;return r.subscribe(function(r){var u,c=!1;try{u=e(r)}catch(a){return i.onError(a),t}if(s)try{c=n(o,u)}catch(a){return i.onError(a),t}s&&c||(s=!0,o=u,i.onNext(r))},i.onError.bind(i),i.onCompleted.bind(i))})},Me["do"]=Me.doAction=function(t,e,n){var r,i=this;return"function"==typeof t?r=t:(r=t.onNext.bind(t),e=t.onError.bind(t),n=t.onCompleted.bind(t)),new on(function(t){return i.subscribe(function(e){try{r(e)}catch(n){t.onError(n)}t.onNext(e)},function(n){if(e){try{e(n)}catch(r){t.onError(r)}t.onError(n)}else t.onError(n)},function(){if(n){try{n()}catch(e){t.onError(e)}t.onCompleted()}else t.onCompleted()})})},Me["finally"]=Me.finallyAction=function(t){var e=this;return new on(function(n){var r;try{r=e.subscribe(n)}catch(i){throw t(),i}return be(function(){try{r.dispose()}catch(e){throw e}finally{t()}})})},Me.ignoreElements=function(){var t=this;return new on(function(e){return t.subscribe(D,e.onError.bind(e),e.onCompleted.bind(e))})},Me.materialize=function(){var t=this;return new on(function(e){return t.subscribe(function(t){e.onNext(je(t))},function(t){e.onNext(Re(t)),e.onCompleted()},function(){e.onNext(ke()),e.onCompleted()})})},Me.repeat=function(t){return Te(this,t).concat()},Me.retry=function(t){return Te(this,t).catchException()},Me.scan=function(){var e,n,r=!1,i=this;return 2===arguments.length?(r=!0,e=arguments[0],n=arguments[1]):n=arguments[0],new on(function(o){var s,u,c;return i.subscribe(function(i){try{c||(c=!0),s?u=n(u,i):(u=r?n(e,i):i,s=!0)}catch(a){return o.onError(a),t}o.onNext(u)},o.onError.bind(o),function(){!c&&r&&o.onNext(e),o.onCompleted()})})},Me.skipLast=function(t){var e=this;return new on(function(n){var r=[];return e.subscribe(function(e){r.push(e),r.length>t&&n.onNext(r.shift())},n.onError.bind(n),n.onCompleted.bind(n))})},Me.startWith=function(){var t,e,n=0;return arguments.length&&"now"in Object(arguments[0])?(e=arguments[0],n=1):e=Ae,t=ie.call(arguments,n),Ve([Je(t,e),this]).concat()},Me.takeLast=function(t,e){return this.takeLastBuffer(t).selectMany(function(t){return Je(t,e)})},Me.takeLastBuffer=function(t){var e=this;return new on(function(n){var r=[];return e.subscribe(function(e){r.push(e),r.length>t&&r.shift()},n.onError.bind(n),function(){n.onNext(r),n.onCompleted()})})},Me.windowWithCount=function(t,e){var n=this;if(0>=t)throw Error(R);if(1===arguments.length&&(e=t),0>=e)throw Error(R);return new on(function(r){var i=new we,o=new Ee(i),s=0,u=[],c=function(){var t=new an;u.push(t),r.onNext(ue(t,o))};return c(),i.setDisposable(n.subscribe(function(n){for(var r,i=0,o=u.length;o>i;i++)u[i].onNext(n);var a=s-t+1;a>=0&&0===a%e&&(r=u.shift(),r.onCompleted()),s++,0===s%e&&c()},function(t){for(;u.length>0;)u.shift().onError(t);r.onError(t)},function(){for(;u.length>0;)u.shift().onCompleted();r.onCompleted()})),o})},Me.selectConcat=Me.concatMap=function(t,e){return e?this.concatMap(function(n,r){var i=t(n,r),o=j(i)?$e(i):i;return o.map(function(t){return e(n,t,r)})}):"function"==typeof t?v.call(this,t):v.call(this,function(){return t})},Me.defaultIfEmpty=function(e){var n=this;return e===t&&(e=null),new on(function(t){var r=!1;return n.subscribe(function(e){r=!0,t.onNext(e)},t.onError.bind(t),function(){r||t.onNext(e),t.onCompleted()})})},Me.distinct=function(e,n){var r=this;return e||(e=S),n||(n=O),new on(function(i){var o={};return r.subscribe(function(r){var s,u,c,a=!1;try{s=e(r),u=n(s)}catch(h){return i.onError(h),t}for(c in o)if(u===c){a=!0;break}a||(o[u]=null,i.onNext(r))},i.onError.bind(i),i.onCompleted.bind(i))})},Me.groupBy=function(t,e,n){return this.groupByUntil(t,e,function(){return Xe()},n)},Me.groupByUntil=function(e,n,r,i){var o=this;return n||(n=S),i||(i=O),new on(function(s){var u={},c=new pe,a=new Ee(c);return c.add(o.subscribe(function(o){var h,l,f,p,d,v,b,m,y,w;try{v=e(o),b=i(v)}catch(g){for(w in u)u[w].onError(g);return s.onError(g),t}p=!1;try{y=u[b],y||(y=new an,u[b]=y,p=!0)}catch(g){for(w in u)u[w].onError(g);return s.onError(g),t}if(p){d=new un(v,y,a),l=new un(v,y);try{h=r(l)}catch(g){for(w in u)u[w].onError(g);return s.onError(g),t}s.onNext(d),m=new we,c.add(m);var E=function(){b in u&&(delete u[b],y.onCompleted()),c.remove(m)};m.setDisposable(h.take(1).subscribe(D,function(t){for(w in u)u[w].onError(t);s.onError(t)},function(){E()}))}try{f=n(o)}catch(g){for(w in u)u[w].onError(g);return s.onError(g),t}y.onNext(f)},function(t){for(var e in u)u[e].onError(t);s.onError(t)},function(){for(var t in u)u[t].onCompleted();s.onCompleted()})),a})},Me.select=Me.map=function(e,n){var r=this;return new on(function(i){var o=0;return r.subscribe(function(s){var u;try{u=e.call(n,s,o++,r)}catch(c){return i.onError(c),t}i.onNext(u)},i.onError.bind(i),i.onCompleted.bind(i))})},Me.pluck=function(t){return this.select(function(e){return e[t]})},Me.selectMany=Me.flatMap=function(t,e){return e?this.selectMany(function(n,r){var i=t(n,r),o=j(i)?$e(i):i;return o.select(function(t){return e(n,t,r)})}):"function"==typeof t?b.call(this,t):b.call(this,function(){return t})},Me.selectSwitch=Me.flatMapLatest=Me.switchMap=function(t,e){return this.select(t,e).switchLatest()},Me.skip=function(t){if(0>t)throw Error(R);var e=this;return new on(function(n){var r=t;return e.subscribe(function(t){0>=r?n.onNext(t):r--},n.onError.bind(n),n.onCompleted.bind(n))})},Me.skipWhile=function(e,n){var r=this;return new on(function(i){var o=0,s=!1;return r.subscribe(function(u){if(!s)try{s=!e.call(n,u,o++,r)}catch(c){return i.onError(c),t}s&&i.onNext(u)},i.onError.bind(i),i.onCompleted.bind(i))})},Me.take=function(t,e){if(0>t)throw Error(R);if(0===t)return Ke(e);var n=this;return new on(function(e){var r=t;return n.subscribe(function(t){r>0&&(r--,e.onNext(t),0===r&&e.onCompleted())},e.onError.bind(e),e.onCompleted.bind(e))})},Me.takeWhile=function(e,n){var r=this;return new on(function(i){var o=0,s=!0;return r.subscribe(function(u){if(s){try{s=e.call(n,u,o++,r)}catch(c){return i.onError(c),t}s?i.onNext(u):i.onCompleted()}},i.onError.bind(i),i.onCompleted.bind(i))})},Me.where=Me.filter=function(e,n){var r=this;return new on(function(i){var o=0;return r.subscribe(function(s){var u;try{u=e.call(n,s,o++,r)}catch(c){return i.onError(c),t}u&&i.onNext(s)},i.onError.bind(i),i.onCompleted.bind(i))})},Me.exclusive=function(){var t=this;return new on(function(e){var n=!1,r=!1,i=new we,o=new pe;return o.add(i),i.setDisposable(t.subscribe(function(t){if(!n){n=!0,j(t)&&(t=$e(t));var i=new we;o.add(i),i.setDisposable(t.subscribe(e.onNext.bind(e),e.onError.bind(e),function(){o.remove(i),n=!1,r&&1===o.length&&e.onCompleted()}))}},e.onError.bind(e),function(){r=!0,n||1!==o.length||e.onCompleted()})),o})},Me.exclusiveMap=function(e,n){var r=this;return new on(function(i){var o=0,s=!1,u=!0,c=new we,a=new pe;return a.add(c),c.setDisposable(r.subscribe(function(r){s||(s=!0,innerSubscription=new we,a.add(innerSubscription),j(r)&&(r=$e(r)),innerSubscription.setDisposable(r.subscribe(function(s){var u;try{u=e.call(n,s,o++,r)}catch(c){return i.onError(c),t}i.onNext(u)},i.onError.bind(i),function(){a.remove(innerSubscription),s=!1,u&&1===a.length&&i.onCompleted()})))},i.onError.bind(i),function(){u=!0,1!==a.length||s||i.onCompleted()})),a})};var on=C.AnonymousObservable=function(e){function n(e){return e===t?e=me:"function"==typeof e&&(e=be(e)),e}function r(i){function o(t){var e=function(){try{r.setDisposable(n(i(r)))}catch(t){if(!r.fail(t))throw t}},r=new sn(t);return Ne.scheduleRequired()?Ne.schedule(e):e(),r}return this instanceof r?(e.call(this,o),t):new r(i)}return oe(r,e),r}(Qe),sn=function(t){function e(e){t.call(this),this.observer=e,this.m=new we}oe(e,t);var n=e.prototype;return n.next=function(t){var e=!1;try{this.observer.onNext(t),e=!0}catch(n){throw n}finally{e||this.dispose()}},n.error=function(t){try{this.observer.onError(t)}catch(e){throw e}finally{this.dispose()}},n.completed=function(){try{this.observer.onCompleted()}catch(t){throw t}finally{this.dispose()}},n.setDisposable=function(t){this.m.setDisposable(t)},n.getDisposable=function(){return this.m.getDisposable()},n.disposable=function(t){return arguments.length?this.getDisposable():setDisposable(t)},n.dispose=function(){t.prototype.dispose.call(this),this.m.dispose()},e}(Ie),un=function(t){function e(t){return this.underlyingObservable.subscribe(t)}function n(n,r,i){t.call(this,e),this.key=n,this.underlyingObservable=i?new on(function(t){return new pe(i.getDisposable(),r.subscribe(t))}):r}return oe(n,t),n}(Qe),cn=function(t,e){this.subject=t,this.observer=e};cn.prototype.dispose=function(){if(!this.subject.isDisposed&&null!==this.observer){var t=this.subject.observers.indexOf(this.observer);this.subject.observers.splice(t,1),this.observer=null}};var an=C.Subject=function(t){function n(t){return e.call(this),this.isStopped?this.exception?(t.onError(this.exception),me):(t.onCompleted(),me):(this.observers.push(t),new cn(this,t))}function r(){t.call(this,n),this.isDisposed=!1,this.isStopped=!1,this.observers=[]}return oe(r,t),se(r.prototype,Le,{hasObservers:function(){return this.observers.length>0},onCompleted:function(){if(e.call(this),!this.isStopped){var t=this.observers.slice(0);this.isStopped=!0;for(var n=0,r=t.length;r>n;n++)t[n].onCompleted();this.observers=[]}},onError:function(t){if(e.call(this),!this.isStopped){var n=this.observers.slice(0);this.isStopped=!0,this.exception=t;for(var r=0,i=n.length;i>r;r++)n[r].onError(t);this.observers=[]}},onNext:function(t){if(e.call(this),!this.isStopped)for(var n=this.observers.slice(0),r=0,i=n.length;i>r;r++)n[r].onNext(t)},dispose:function(){this.isDisposed=!0,this.observers=null}}),r.create=function(t,e){return new hn(t,e)},r}(Qe);C.AsyncSubject=function(t){function n(t){if(e.call(this),!this.isStopped)return this.observers.push(t),new cn(this,t);var n=this.exception,r=this.hasValue,i=this.value;return n?t.onError(n):r?(t.onNext(i),t.onCompleted()):t.onCompleted(),me}function r(){t.call(this,n),this.isDisposed=!1,this.isStopped=!1,this.value=null,this.hasValue=!1,this.observers=[],this.exception=null}return oe(r,t),se(r.prototype,Le,{hasObservers:function(){return e.call(this),this.observers.length>0},onCompleted:function(){var t,n,r;if(e.call(this),!this.isStopped){this.isStopped=!0;var i=this.observers.slice(0),o=this.value,s=this.hasValue;if(s)for(n=0,r=i.length;r>n;n++)t=i[n],t.onNext(o),t.onCompleted();else for(n=0,r=i.length;r>n;n++)i[n].onCompleted();this.observers=[]}},onError:function(t){if(e.call(this),!this.isStopped){var n=this.observers.slice(0);this.isStopped=!0,this.exception=t;for(var r=0,i=n.length;i>r;r++)n[r].onError(t);this.observers=[]}},onNext:function(t){e.call(this),this.isStopped||(this.value=t,this.hasValue=!0)},dispose:function(){this.isDisposed=!0,this.observers=null,this.exception=null,this.value=null}}),r}(Qe);var hn=function(t){function e(t){return this.observable.subscribe(t)}function n(n,r){t.call(this,e),this.observer=n,this.observable=r}return oe(n,t),se(n.prototype,Le,{onCompleted:function(){this.observer.onCompleted()},onError:function(t){this.observer.onError(t)},onNext:function(t){this.observer.onNext(t)}}),n}(Qe);"function"==typeof define&&"object"==typeof define.amd&&define.amd?(y.Rx=C,define(function(){return C})):w&&g?E?(g.exports=C).Rx=C:w.Rx=C:y.Rx=C}).call(this); \ No newline at end of file diff --git a/ajax/libs/rxjs/2.2.28/rx.core.compat.js b/ajax/libs/rxjs/2.2.28/rx.core.compat.js new file mode 100644 index 000000000..3c9b38f5d --- /dev/null +++ b/ajax/libs/rxjs/2.2.28/rx.core.compat.js @@ -0,0 +1,2627 @@ +// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. + +;(function (undefined) { + + var objectTypes = { + 'boolean': false, + 'function': true, + 'object': true, + 'number': false, + 'string': false, + 'undefined': false + }; + + var root = (objectTypes[typeof window] && window) || this, + freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports, + freeModule = objectTypes[typeof module] && module && !module.nodeType && module, + moduleExports = freeModule && freeModule.exports === freeExports && freeExports, + freeGlobal = objectTypes[typeof global] && global; + + if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal)) { + root = freeGlobal; + } + + var Rx = { + internals: {}, + config: { + Promise: root.Promise // Detect if promise exists + }, + helpers: { } + }; + + // Defaults + var noop = Rx.helpers.noop = function () { }, + identity = Rx.helpers.identity = function (x) { return x; }, + pluck = Rx.helpers.pluck = function (property) { return function (x) { return x[property]; }; }, + just = Rx.helpers.just = function (value) { return function () { return value; }; }, + defaultNow = Rx.helpers.defaultNow = (function () { return !!Date.now ? Date.now : function () { return +new Date; }; }()), + defaultComparer = Rx.helpers.defaultComparer = function (x, y) { return isEqual(x, y); }, + defaultSubComparer = Rx.helpers.defaultSubComparer = function (x, y) { return x > y ? 1 : (x < y ? -1 : 0); }, + defaultKeySerializer = Rx.helpers.defaultKeySerializer = function (x) { return x.toString(); }, + defaultError = Rx.helpers.defaultError = function (err) { throw err; }, + isPromise = Rx.helpers.isPromise = function (p) { return !!p && typeof p.then === 'function' && p.then !== Rx.Observable.prototype.then; }, + asArray = Rx.helpers.asArray = function () { return Array.prototype.slice.call(arguments); }, + not = Rx.helpers.not = function (a) { return !a; }; + + // Errors + var sequenceContainsNoElements = 'Sequence contains no elements.'; + var argumentOutOfRange = 'Argument out of range'; + var objectDisposed = 'Object has been disposed'; + function checkDisposed() { if (this.isDisposed) { throw new Error(objectDisposed); } } + + // Shim in iterator support + var $iterator$ = (typeof Symbol === 'object' && Symbol.iterator) || + '_es6shim_iterator_'; + // Firefox ships a partial implementation using the name @@iterator. + // https://bugzilla.mozilla.org/show_bug.cgi?id=907077#c14 + // So use that name if we detect it. + if (root.Set && typeof new root.Set()['@@iterator'] === 'function') { + $iterator$ = '@@iterator'; + } + var doneEnumerator = { done: true, value: undefined }; + + /** `Object#toString` result shortcuts */ + var argsClass = '[object Arguments]', + arrayClass = '[object Array]', + boolClass = '[object Boolean]', + dateClass = '[object Date]', + errorClass = '[object Error]', + funcClass = '[object Function]', + numberClass = '[object Number]', + objectClass = '[object Object]', + regexpClass = '[object RegExp]', + stringClass = '[object String]'; + + var toString = Object.prototype.toString, + hasOwnProperty = Object.prototype.hasOwnProperty, + supportsArgsClass = toString.call(arguments) == argsClass, // For less -1); + } + }); + } + } + stackA.pop(); + stackB.pop(); + + return result; + } + var slice = Array.prototype.slice; + function argsOrArray(args, idx) { + return args.length === 1 && Array.isArray(args[idx]) ? + args[idx] : + slice.call(args); + } + var hasProp = {}.hasOwnProperty; + + /** @private */ + var inherits = this.inherits = Rx.internals.inherits = function (child, parent) { + function __() { this.constructor = child; } + __.prototype = parent.prototype; + child.prototype = new __(); + }; + + /** @private */ + var addProperties = Rx.internals.addProperties = function (obj) { + var sources = slice.call(arguments, 1); + for (var i = 0, len = sources.length; i < len; i++) { + var source = sources[i]; + for (var prop in source) { + obj[prop] = source[prop]; + } + } + }; + + // Rx Utils + var addRef = Rx.internals.addRef = function (xs, r) { + return new AnonymousObservable(function (observer) { + return new CompositeDisposable(r.getDisposable(), xs.subscribe(observer)); + }); + }; + + // Collection polyfills + function arrayInitialize(count, factory) { + var a = new Array(count); + for (var i = 0; i < count; i++) { + a[i] = factory(); + } + return a; + } + + // Utilities + if (!Function.prototype.bind) { + Function.prototype.bind = function (that) { + var target = this, + args = slice.call(arguments, 1); + var bound = function () { + if (this instanceof bound) { + function F() { } + F.prototype = target.prototype; + var self = new F(); + var result = target.apply(self, args.concat(slice.call(arguments))); + if (Object(result) === result) { + return result; + } + return self; + } else { + return target.apply(that, args.concat(slice.call(arguments))); + } + }; + + return bound; + }; + } + + var boxedString = Object("a"), + splitString = boxedString[0] != "a" || !(0 in boxedString); + if (!Array.prototype.every) { + Array.prototype.every = function every(fun /*, thisp */) { + var object = Object(this), + self = splitString && {}.toString.call(this) == stringClass ? + this.split("") : + object, + length = self.length >>> 0, + thisp = arguments[1]; + + if ({}.toString.call(fun) != funcClass) { + throw new TypeError(fun + " is not a function"); + } + + for (var i = 0; i < length; i++) { + if (i in self && !fun.call(thisp, self[i], i, object)) { + return false; + } + } + return true; + }; + } + + if (!Array.prototype.map) { + Array.prototype.map = function map(fun /*, thisp*/) { + var object = Object(this), + self = splitString && {}.toString.call(this) == stringClass ? + this.split("") : + object, + length = self.length >>> 0, + result = Array(length), + thisp = arguments[1]; + + if ({}.toString.call(fun) != funcClass) { + throw new TypeError(fun + " is not a function"); + } + + for (var i = 0; i < length; i++) { + if (i in self) + result[i] = fun.call(thisp, self[i], i, object); + } + return result; + }; + } + + if (!Array.prototype.filter) { + Array.prototype.filter = function (predicate) { + var results = [], item, t = new Object(this); + for (var i = 0, len = t.length >>> 0; i < len; i++) { + item = t[i]; + if (i in t && predicate.call(arguments[1], item, i, t)) { + results.push(item); + } + } + return results; + }; + } + + if (!Array.isArray) { + Array.isArray = function (arg) { + return Object.prototype.toString.call(arg) == arrayClass; + }; + } + + if (!Array.prototype.indexOf) { + Array.prototype.indexOf = function indexOf(searchElement) { + var t = Object(this); + var len = t.length >>> 0; + if (len === 0) { + return -1; + } + var n = 0; + if (arguments.length > 1) { + n = Number(arguments[1]); + if (n !== n) { + n = 0; + } else if (n !== 0 && n != Infinity && n !== -Infinity) { + n = (n > 0 || -1) * Math.floor(Math.abs(n)); + } + } + if (n >= len) { + return -1; + } + var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0); + for (; k < len; k++) { + if (k in t && t[k] === searchElement) { + return k; + } + } + return -1; + }; + } + + // Collections + var IndexedItem = function (id, value) { + this.id = id; + this.value = value; + }; + + IndexedItem.prototype.compareTo = function (other) { + var c = this.value.compareTo(other.value); + if (c === 0) { + c = this.id - other.id; + } + return c; + }; + + // Priority Queue for Scheduling + var PriorityQueue = Rx.internals.PriorityQueue = function (capacity) { + this.items = new Array(capacity); + this.length = 0; + }; + + var priorityProto = PriorityQueue.prototype; + priorityProto.isHigherPriority = function (left, right) { + return this.items[left].compareTo(this.items[right]) < 0; + }; + + priorityProto.percolate = function (index) { + if (index >= this.length || index < 0) { + return; + } + var parent = index - 1 >> 1; + if (parent < 0 || parent === index) { + return; + } + if (this.isHigherPriority(index, parent)) { + var temp = this.items[index]; + this.items[index] = this.items[parent]; + this.items[parent] = temp; + this.percolate(parent); + } + }; + + priorityProto.heapify = function (index) { + if (index === undefined) { + index = 0; + } + if (index >= this.length || index < 0) { + return; + } + var left = 2 * index + 1, + right = 2 * index + 2, + first = index; + if (left < this.length && this.isHigherPriority(left, first)) { + first = left; + } + if (right < this.length && this.isHigherPriority(right, first)) { + first = right; + } + if (first !== index) { + var temp = this.items[index]; + this.items[index] = this.items[first]; + this.items[first] = temp; + this.heapify(first); + } + }; + + priorityProto.peek = function () { return this.items[0].value; }; + + priorityProto.removeAt = function (index) { + this.items[index] = this.items[--this.length]; + delete this.items[this.length]; + this.heapify(); + }; + + priorityProto.dequeue = function () { + var result = this.peek(); + this.removeAt(0); + return result; + }; + + priorityProto.enqueue = function (item) { + var index = this.length++; + this.items[index] = new IndexedItem(PriorityQueue.count++, item); + this.percolate(index); + }; + + priorityProto.remove = function (item) { + for (var i = 0; i < this.length; i++) { + if (this.items[i].value === item) { + this.removeAt(i); + return true; + } + } + return false; + }; + PriorityQueue.count = 0; + /** + * Represents a group of disposable resources that are disposed together. + * @constructor + */ + var CompositeDisposable = Rx.CompositeDisposable = function () { + this.disposables = argsOrArray(arguments, 0); + this.isDisposed = false; + this.length = this.disposables.length; + }; + + var CompositeDisposablePrototype = CompositeDisposable.prototype; + + /** + * Adds a disposable to the CompositeDisposable or disposes the disposable if the CompositeDisposable is disposed. + * @param {Mixed} item Disposable to add. + */ + CompositeDisposablePrototype.add = function (item) { + if (this.isDisposed) { + item.dispose(); + } else { + this.disposables.push(item); + this.length++; + } + }; + + /** + * Removes and disposes the first occurrence of a disposable from the CompositeDisposable. + * @param {Mixed} item Disposable to remove. + * @returns {Boolean} true if found; false otherwise. + */ + CompositeDisposablePrototype.remove = function (item) { + var shouldDispose = false; + if (!this.isDisposed) { + var idx = this.disposables.indexOf(item); + if (idx !== -1) { + shouldDispose = true; + this.disposables.splice(idx, 1); + this.length--; + item.dispose(); + } + + } + return shouldDispose; + }; + + /** + * Disposes all disposables in the group and removes them from the group. + */ + CompositeDisposablePrototype.dispose = function () { + if (!this.isDisposed) { + this.isDisposed = true; + var currentDisposables = this.disposables.slice(0); + this.disposables = []; + this.length = 0; + + for (var i = 0, len = currentDisposables.length; i < len; i++) { + currentDisposables[i].dispose(); + } + } + }; + + /** + * Removes and disposes all disposables from the CompositeDisposable, but does not dispose the CompositeDisposable. + */ + CompositeDisposablePrototype.clear = function () { + var currentDisposables = this.disposables.slice(0); + this.disposables = []; + this.length = 0; + for (var i = 0, len = currentDisposables.length; i < len; i++) { + currentDisposables[i].dispose(); + } + }; + + /** + * Determines whether the CompositeDisposable contains a specific disposable. + * @param {Mixed} item Disposable to search for. + * @returns {Boolean} true if the disposable was found; otherwise, false. + */ + CompositeDisposablePrototype.contains = function (item) { + return this.disposables.indexOf(item) !== -1; + }; + + /** + * Converts the existing CompositeDisposable to an array of disposables + * @returns {Array} An array of disposable objects. + */ + CompositeDisposablePrototype.toArray = function () { + return this.disposables.slice(0); + }; + + /** + * Provides a set of static methods for creating Disposables. + * + * @constructor + * @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once. + */ + var Disposable = Rx.Disposable = function (action) { + this.isDisposed = false; + this.action = action || noop; + }; + + /** Performs the task of cleaning up resources. */ + Disposable.prototype.dispose = function () { + if (!this.isDisposed) { + this.action(); + this.isDisposed = true; + } + }; + + /** + * Creates a disposable object that invokes the specified action when disposed. + * @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once. + * @return {Disposable} The disposable object that runs the given action upon disposal. + */ + var disposableCreate = Disposable.create = function (action) { return new Disposable(action); }; + + /** + * Gets the disposable that does nothing when disposed. + */ + var disposableEmpty = Disposable.empty = { dispose: noop }; + + var BooleanDisposable = (function () { + function BooleanDisposable (isSingle) { + this.isSingle = isSingle; + this.isDisposed = false; + this.current = null; + } + + var booleanDisposablePrototype = BooleanDisposable.prototype; + + /** + * Gets the underlying disposable. + * @return The underlying disposable. + */ + booleanDisposablePrototype.getDisposable = function () { + return this.current; + }; + + /** + * Sets the underlying disposable. + * @param {Disposable} value The new underlying disposable. + */ + booleanDisposablePrototype.setDisposable = function (value) { + if (this.current && this.isSingle) { + throw new Error('Disposable has already been assigned'); + } + + var shouldDispose = this.isDisposed, old; + if (!shouldDispose) { + old = this.current; + this.current = value; + } + if (old) { + old.dispose(); + } + if (shouldDispose && value) { + value.dispose(); + } + }; + + /** + * Disposes the underlying disposable as well as all future replacements. + */ + booleanDisposablePrototype.dispose = function () { + var old; + if (!this.isDisposed) { + this.isDisposed = true; + old = this.current; + this.current = null; + } + if (old) { + old.dispose(); + } + }; + + return BooleanDisposable; + }()); + + /** + * Represents a disposable resource which only allows a single assignment of its underlying disposable resource. + * If an underlying disposable resource has already been set, future attempts to set the underlying disposable resource will throw an Error. + */ + var SingleAssignmentDisposable = Rx.SingleAssignmentDisposable = (function (super_) { + inherits(SingleAssignmentDisposable, super_); + + function SingleAssignmentDisposable() { + super_.call(this, true); + } + + return SingleAssignmentDisposable; + }(BooleanDisposable)); + + /** + * Represents a disposable resource whose underlying disposable resource can be replaced by another disposable resource, causing automatic disposal of the previous underlying disposable resource. + */ + var SerialDisposable = Rx.SerialDisposable = (function (super_) { + inherits(SerialDisposable, super_); + + function SerialDisposable() { + super_.call(this, false); + } + + return SerialDisposable; + }(BooleanDisposable)); + + /** + * Represents a disposable resource that only disposes its underlying disposable resource when all dependent disposable objects have been disposed. + */ + var RefCountDisposable = Rx.RefCountDisposable = (function () { + + function InnerDisposable(disposable) { + this.disposable = disposable; + this.disposable.count++; + this.isInnerDisposed = false; + } + + InnerDisposable.prototype.dispose = function () { + if (!this.disposable.isDisposed) { + if (!this.isInnerDisposed) { + this.isInnerDisposed = true; + this.disposable.count--; + if (this.disposable.count === 0 && this.disposable.isPrimaryDisposed) { + this.disposable.isDisposed = true; + this.disposable.underlyingDisposable.dispose(); + } + } + } + }; + + /** + * Initializes a new instance of the RefCountDisposable with the specified disposable. + * @constructor + * @param {Disposable} disposable Underlying disposable. + */ + function RefCountDisposable(disposable) { + this.underlyingDisposable = disposable; + this.isDisposed = false; + this.isPrimaryDisposed = false; + this.count = 0; + } + + /** + * Disposes the underlying disposable only when all dependent disposables have been disposed + */ + RefCountDisposable.prototype.dispose = function () { + if (!this.isDisposed) { + if (!this.isPrimaryDisposed) { + this.isPrimaryDisposed = true; + if (this.count === 0) { + this.isDisposed = true; + this.underlyingDisposable.dispose(); + } + } + } + }; + + /** + * Returns a dependent disposable that when disposed decreases the refcount on the underlying disposable. + * @returns {Disposable} A dependent disposable contributing to the reference count that manages the underlying disposable's lifetime. + */ + RefCountDisposable.prototype.getDisposable = function () { + return this.isDisposed ? disposableEmpty : new InnerDisposable(this); + }; + + return RefCountDisposable; + })(); + + function ScheduledDisposable(scheduler, disposable) { + this.scheduler = scheduler; + this.disposable = disposable; + this.isDisposed = false; + } + + ScheduledDisposable.prototype.dispose = function () { + var parent = this; + this.scheduler.schedule(function () { + if (!parent.isDisposed) { + parent.isDisposed = true; + parent.disposable.dispose(); + } + }); + }; + + var ScheduledItem = Rx.internals.ScheduledItem = function (scheduler, state, action, dueTime, comparer) { + this.scheduler = scheduler; + this.state = state; + this.action = action; + this.dueTime = dueTime; + this.comparer = comparer || defaultSubComparer; + this.disposable = new SingleAssignmentDisposable(); + } + + ScheduledItem.prototype.invoke = function () { + this.disposable.setDisposable(this.invokeCore()); + }; + + ScheduledItem.prototype.compareTo = function (other) { + return this.comparer(this.dueTime, other.dueTime); + }; + + ScheduledItem.prototype.isCancelled = function () { + return this.disposable.isDisposed; + }; + + ScheduledItem.prototype.invokeCore = function () { + return this.action(this.scheduler, this.state); + }; + + /** Provides a set of static properties to access commonly used schedulers. */ + var Scheduler = Rx.Scheduler = (function () { + + /** + * @constructor + * @private + */ + function Scheduler(now, schedule, scheduleRelative, scheduleAbsolute) { + this.now = now; + this._schedule = schedule; + this._scheduleRelative = scheduleRelative; + this._scheduleAbsolute = scheduleAbsolute; + } + + function invokeRecImmediate(scheduler, pair) { + var state = pair.first, action = pair.second, group = new CompositeDisposable(), + recursiveAction = function (state1) { + action(state1, function (state2) { + var isAdded = false, isDone = false, + d = scheduler.scheduleWithState(state2, function (scheduler1, state3) { + if (isAdded) { + group.remove(d); + } else { + isDone = true; + } + recursiveAction(state3); + return disposableEmpty; + }); + if (!isDone) { + group.add(d); + isAdded = true; + } + }); + }; + recursiveAction(state); + return group; + } + + function invokeRecDate(scheduler, pair, method) { + var state = pair.first, action = pair.second, group = new CompositeDisposable(), + recursiveAction = function (state1) { + action(state1, function (state2, dueTime1) { + var isAdded = false, isDone = false, + d = scheduler[method].call(scheduler, state2, dueTime1, function (scheduler1, state3) { + if (isAdded) { + group.remove(d); + } else { + isDone = true; + } + recursiveAction(state3); + return disposableEmpty; + }); + if (!isDone) { + group.add(d); + isAdded = true; + } + }); + }; + recursiveAction(state); + return group; + } + + function invokeAction(scheduler, action) { + action(); + return disposableEmpty; + } + + var schedulerProto = Scheduler.prototype; + + /** + * Returns a scheduler that wraps the original scheduler, adding exception handling for scheduled actions. + * @param {Function} handler Handler that's run if an exception is caught. The exception will be rethrown if the handler returns false. + * @returns {Scheduler} Wrapper around the original scheduler, enforcing exception handling. + */ + schedulerProto.catchException = schedulerProto['catch'] = function (handler) { + return new CatchScheduler(this, handler); + }; + + /** + * Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation. + * @param {Number} period Period for running the work periodically. + * @param {Function} action Action to be executed. + * @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort). + */ + schedulerProto.schedulePeriodic = function (period, action) { + return this.schedulePeriodicWithState(null, period, function () { + action(); + }); + }; + + /** + * Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation. + * @param {Mixed} state Initial state passed to the action upon the first iteration. + * @param {Number} period Period for running the work periodically. + * @param {Function} action Action to be executed, potentially updating the state. + * @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort). + */ + schedulerProto.schedulePeriodicWithState = function (state, period, action) { + var s = state, id = setInterval(function () { + s = action(s); + }, period); + return disposableCreate(function () { + clearInterval(id); + }); + }; + + /** + * Schedules an action to be executed. + * @param {Function} action Action to execute. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.schedule = function (action) { + return this._schedule(action, invokeAction); + }; + + /** + * Schedules an action to be executed. + * @param state State passed to the action to be executed. + * @param {Function} action Action to be executed. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleWithState = function (state, action) { + return this._schedule(state, action); + }; + + /** + * Schedules an action to be executed after the specified relative due time. + * @param {Function} action Action to execute. + * @param {Number} dueTime Relative time after which to execute the action. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleWithRelative = function (dueTime, action) { + return this._scheduleRelative(action, dueTime, invokeAction); + }; + + /** + * Schedules an action to be executed after dueTime. + * @param state State passed to the action to be executed. + * @param {Function} action Action to be executed. + * @param {Number} dueTime Relative time after which to execute the action. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleWithRelativeAndState = function (state, dueTime, action) { + return this._scheduleRelative(state, dueTime, action); + }; + + /** + * Schedules an action to be executed at the specified absolute due time. + * @param {Function} action Action to execute. + * @param {Number} dueTime Absolute time at which to execute the action. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleWithAbsolute = function (dueTime, action) { + return this._scheduleAbsolute(action, dueTime, invokeAction); + }; + + /** + * Schedules an action to be executed at dueTime. + * @param {Mixed} state State passed to the action to be executed. + * @param {Function} action Action to be executed. + * @param {Number}dueTime Absolute time at which to execute the action. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleWithAbsoluteAndState = function (state, dueTime, action) { + return this._scheduleAbsolute(state, dueTime, action); + }; + + /** + * Schedules an action to be executed recursively. + * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleRecursive = function (action) { + return this.scheduleRecursiveWithState(action, function (_action, self) { + _action(function () { + self(_action); + }); + }); + }; + + /** + * Schedules an action to be executed recursively. + * @param {Mixed} state State passed to the action to be executed. + * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in recursive invocation state. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleRecursiveWithState = function (state, action) { + return this.scheduleWithState({ first: state, second: action }, function (s, p) { + return invokeRecImmediate(s, p); + }); + }; + + /** + * Schedules an action to be executed recursively after a specified relative due time. + * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified relative time. + * @param {Number}dueTime Relative time after which to execute the action for the first time. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleRecursiveWithRelative = function (dueTime, action) { + return this.scheduleRecursiveWithRelativeAndState(action, dueTime, function (_action, self) { + _action(function (dt) { + self(_action, dt); + }); + }); + }; + + /** + * Schedules an action to be executed recursively after a specified relative due time. + * @param {Mixed} state State passed to the action to be executed. + * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state. + * @param {Number}dueTime Relative time after which to execute the action for the first time. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleRecursiveWithRelativeAndState = function (state, dueTime, action) { + return this._scheduleRelative({ first: state, second: action }, dueTime, function (s, p) { + return invokeRecDate(s, p, 'scheduleWithRelativeAndState'); + }); + }; + + /** + * Schedules an action to be executed recursively at a specified absolute due time. + * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified absolute time. + * @param {Number}dueTime Absolute time at which to execute the action for the first time. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleRecursiveWithAbsolute = function (dueTime, action) { + return this.scheduleRecursiveWithAbsoluteAndState(action, dueTime, function (_action, self) { + _action(function (dt) { + self(_action, dt); + }); + }); + }; + + /** + * Schedules an action to be executed recursively at a specified absolute due time. + * @param {Mixed} state State passed to the action to be executed. + * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state. + * @param {Number}dueTime Absolute time at which to execute the action for the first time. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleRecursiveWithAbsoluteAndState = function (state, dueTime, action) { + return this._scheduleAbsolute({ first: state, second: action }, dueTime, function (s, p) { + return invokeRecDate(s, p, 'scheduleWithAbsoluteAndState'); + }); + }; + + /** Gets the current time according to the local machine's system clock. */ + Scheduler.now = defaultNow; + + /** + * Normalizes the specified TimeSpan value to a positive value. + * @param {Number} timeSpan The time span value to normalize. + * @returns {Number} The specified TimeSpan value if it is zero or positive; otherwise, 0 + */ + Scheduler.normalize = function (timeSpan) { + if (timeSpan < 0) { + timeSpan = 0; + } + return timeSpan; + }; + + return Scheduler; + }()); + + var normalizeTime = Scheduler.normalize; + + var SchedulePeriodicRecursive = Rx.internals.SchedulePeriodicRecursive = (function () { + function tick(command, recurse) { + recurse(0, this._period); + try { + this._state = this._action(this._state); + } catch (e) { + this._cancel.dispose(); + throw e; + } + } + + function SchedulePeriodicRecursive(scheduler, state, period, action) { + this._scheduler = scheduler; + this._state = state; + this._period = period; + this._action = action; + } + + SchedulePeriodicRecursive.prototype.start = function () { + var d = new SingleAssignmentDisposable(); + this._cancel = d; + d.setDisposable(this._scheduler.scheduleRecursiveWithRelativeAndState(0, this._period, tick.bind(this))); + + return d; + }; + + return SchedulePeriodicRecursive; + }()); + + /** + * Gets a scheduler that schedules work immediately on the current thread. + */ + var immediateScheduler = Scheduler.immediate = (function () { + + function scheduleNow(state, action) { return action(this, state); } + + function scheduleRelative(state, dueTime, action) { + var dt = normalizeTime(dt); + while (dt - this.now() > 0) { } + return action(this, state); + } + + function scheduleAbsolute(state, dueTime, action) { + return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); + } + + return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); + }()); + + /** + * Gets a scheduler that schedules work as soon as possible on the current thread. + */ + var currentThreadScheduler = Scheduler.currentThread = (function () { + var queue; + + function runTrampoline (q) { + var item; + while (q.length > 0) { + item = q.dequeue(); + if (!item.isCancelled()) { + // Note, do not schedule blocking work! + while (item.dueTime - Scheduler.now() > 0) { + } + if (!item.isCancelled()) { + item.invoke(); + } + } + } + } + + function scheduleNow(state, action) { + return this.scheduleWithRelativeAndState(state, 0, action); + } + + function scheduleRelative(state, dueTime, action) { + var dt = this.now() + Scheduler.normalize(dueTime), + si = new ScheduledItem(this, state, action, dt), + t; + if (!queue) { + queue = new PriorityQueue(4); + queue.enqueue(si); + try { + runTrampoline(queue); + } catch (e) { + throw e; + } finally { + queue = null; + } + } else { + queue.enqueue(si); + } + return si.disposable; + } + + function scheduleAbsolute(state, dueTime, action) { + return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); + } + + var currentScheduler = new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); + currentScheduler.scheduleRequired = function () { return queue === null; }; + currentScheduler.ensureTrampoline = function (action) { + if (queue === null) { + return this.schedule(action); + } else { + return action(); + } + }; + + return currentScheduler; + }()); + + + var scheduleMethod, clearMethod = noop; + (function () { + + var reNative = RegExp('^' + + String(toString) + .replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + .replace(/toString| for [^\]]+/g, '.*?') + '$' + ); + + var setImmediate = typeof (setImmediate = freeGlobal && moduleExports && freeGlobal.setImmediate) == 'function' && + !reNative.test(setImmediate) && setImmediate, + clearImmediate = typeof (clearImmediate = freeGlobal && moduleExports && freeGlobal.clearImmediate) == 'function' && + !reNative.test(clearImmediate) && clearImmediate; + + function postMessageSupported () { + // Ensure not in a worker + if (!root.postMessage || root.importScripts) { return false; } + var isAsync = false, + oldHandler = root.onmessage; + // Test for async + root.onmessage = function () { isAsync = true; }; + root.postMessage('','*'); + root.onmessage = oldHandler; + + return isAsync; + } + + // Use in order, nextTick, setImmediate, postMessage, MessageChannel, script readystatechanged, setTimeout + if (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]') { + scheduleMethod = process.nextTick; + } else if (typeof setImmediate === 'function') { + scheduleMethod = setImmediate; + clearMethod = clearImmediate; + } else if (postMessageSupported()) { + var MSG_PREFIX = 'ms.rx.schedule' + Math.random(), + tasks = {}, + taskId = 0; + + function onGlobalPostMessage(event) { + // Only if we're a match to avoid any other global events + if (typeof event.data === 'string' && event.data.substring(0, MSG_PREFIX.length) === MSG_PREFIX) { + var handleId = event.data.substring(MSG_PREFIX.length), + action = tasks[handleId]; + action(); + delete tasks[handleId]; + } + } + + if (root.addEventListener) { + root.addEventListener('message', onGlobalPostMessage, false); + } else { + root.attachEvent('onmessage', onGlobalPostMessage, false); + } + + scheduleMethod = function (action) { + var currentId = taskId++; + tasks[currentId] = action; + root.postMessage(MSG_PREFIX + currentId, '*'); + }; + } else if (!!root.MessageChannel) { + var channel = new root.MessageChannel(), + channelTasks = {}, + channelTaskId = 0; + + channel.port1.onmessage = function (event) { + var id = event.data, + action = channelTasks[id]; + action(); + delete channelTasks[id]; + }; + + scheduleMethod = function (action) { + var id = channelTaskId++; + channelTasks[id] = action; + channel.port2.postMessage(id); + }; + } else if ('document' in root && 'onreadystatechange' in root.document.createElement('script')) { + + scheduleMethod = function (action) { + var scriptElement = root.document.createElement('script'); + scriptElement.onreadystatechange = function () { + action(); + scriptElement.onreadystatechange = null; + scriptElement.parentNode.removeChild(scriptElement); + scriptElement = null; + }; + root.document.documentElement.appendChild(scriptElement); + }; + + } else { + scheduleMethod = function (action) { return setTimeout(action, 0); }; + clearMethod = clearTimeout; + } + }()); + + /** + * Gets a scheduler that schedules work via a timed callback based upon platform. + */ + var timeoutScheduler = Scheduler.timeout = (function () { + + function scheduleNow(state, action) { + var scheduler = this, + disposable = new SingleAssignmentDisposable(); + var id = scheduleMethod(function () { + if (!disposable.isDisposed) { + disposable.setDisposable(action(scheduler, state)); + } + }); + return new CompositeDisposable(disposable, disposableCreate(function () { + clearMethod(id); + })); + } + + function scheduleRelative(state, dueTime, action) { + var scheduler = this, + dt = Scheduler.normalize(dueTime); + if (dt === 0) { + return scheduler.scheduleWithState(state, action); + } + var disposable = new SingleAssignmentDisposable(); + var id = setTimeout(function () { + if (!disposable.isDisposed) { + disposable.setDisposable(action(scheduler, state)); + } + }, dt); + return new CompositeDisposable(disposable, disposableCreate(function () { + clearTimeout(id); + })); + } + + function scheduleAbsolute(state, dueTime, action) { + return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); + } + + return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); + })(); + + /** @private */ + var CatchScheduler = (function (_super) { + + function localNow() { + return this._scheduler.now(); + } + + function scheduleNow(state, action) { + return this._scheduler.scheduleWithState(state, this._wrap(action)); + } + + function scheduleRelative(state, dueTime, action) { + return this._scheduler.scheduleWithRelativeAndState(state, dueTime, this._wrap(action)); + } + + function scheduleAbsolute(state, dueTime, action) { + return this._scheduler.scheduleWithAbsoluteAndState(state, dueTime, this._wrap(action)); + } + + inherits(CatchScheduler, _super); + + /** @private */ + function CatchScheduler(scheduler, handler) { + this._scheduler = scheduler; + this._handler = handler; + this._recursiveOriginal = null; + this._recursiveWrapper = null; + _super.call(this, localNow, scheduleNow, scheduleRelative, scheduleAbsolute); + } + + /** @private */ + CatchScheduler.prototype._clone = function (scheduler) { + return new CatchScheduler(scheduler, this._handler); + }; + + /** @private */ + CatchScheduler.prototype._wrap = function (action) { + var parent = this; + return function (self, state) { + try { + return action(parent._getRecursiveWrapper(self), state); + } catch (e) { + if (!parent._handler(e)) { throw e; } + return disposableEmpty; + } + }; + }; + + /** @private */ + CatchScheduler.prototype._getRecursiveWrapper = function (scheduler) { + if (this._recursiveOriginal !== scheduler) { + this._recursiveOriginal = scheduler; + var wrapper = this._clone(scheduler); + wrapper._recursiveOriginal = scheduler; + wrapper._recursiveWrapper = wrapper; + this._recursiveWrapper = wrapper; + } + return this._recursiveWrapper; + }; + + /** @private */ + CatchScheduler.prototype.schedulePeriodicWithState = function (state, period, action) { + var self = this, failed = false, d = new SingleAssignmentDisposable(); + + d.setDisposable(this._scheduler.schedulePeriodicWithState(state, period, function (state1) { + if (failed) { return null; } + try { + return action(state1); + } catch (e) { + failed = true; + if (!self._handler(e)) { throw e; } + d.dispose(); + return null; + } + })); + + return d; + }; + + return CatchScheduler; + }(Scheduler)); + + /** + * Represents a notification to an observer. + */ + var Notification = Rx.Notification = (function () { + function Notification(kind, hasValue) { + this.hasValue = hasValue == null ? false : hasValue; + this.kind = kind; + } + + var NotificationPrototype = Notification.prototype; + + /** + * Invokes the delegate corresponding to the notification or the observer's method corresponding to the notification and returns the produced result. + * + * @memberOf Notification + * @param {Any} observerOrOnNext Delegate to invoke for an OnNext notification or Observer to invoke the notification on.. + * @param {Function} onError Delegate to invoke for an OnError notification. + * @param {Function} onCompleted Delegate to invoke for an OnCompleted notification. + * @returns {Any} Result produced by the observation. + */ + NotificationPrototype.accept = function (observerOrOnNext, onError, onCompleted) { + if (arguments.length === 1 && typeof observerOrOnNext === 'object') { + return this._acceptObservable(observerOrOnNext); + } + return this._accept(observerOrOnNext, onError, onCompleted); + }; + + /** + * Returns an observable sequence with a single notification. + * + * @memberOf Notification + * @param {Scheduler} [scheduler] Scheduler to send out the notification calls on. + * @returns {Observable} The observable sequence that surfaces the behavior of the notification upon subscription. + */ + NotificationPrototype.toObservable = function (scheduler) { + var notification = this; + scheduler || (scheduler = immediateScheduler); + return new AnonymousObservable(function (observer) { + return scheduler.schedule(function () { + notification._acceptObservable(observer); + if (notification.kind === 'N') { + observer.onCompleted(); + } + }); + }); + }; + + return Notification; + })(); + + /** + * Creates an object that represents an OnNext notification to an observer. + * @param {Any} value The value contained in the notification. + * @returns {Notification} The OnNext notification containing the value. + */ + var notificationCreateOnNext = Notification.createOnNext = (function () { + + function _accept (onNext) { + return onNext(this.value); + } + + function _acceptObservable(observer) { + return observer.onNext(this.value); + } + + function toString () { + return 'OnNext(' + this.value + ')'; + } + + return function (value) { + var notification = new Notification('N', true); + notification.value = value; + notification._accept = _accept; + notification._acceptObservable = _acceptObservable; + notification.toString = toString; + return notification; + }; + }()); + + /** + * Creates an object that represents an OnError notification to an observer. + * @param {Any} error The exception contained in the notification. + * @returns {Notification} The OnError notification containing the exception. + */ + var notificationCreateOnError = Notification.createOnError = (function () { + + function _accept (onNext, onError) { + return onError(this.exception); + } + + function _acceptObservable(observer) { + return observer.onError(this.exception); + } + + function toString () { + return 'OnError(' + this.exception + ')'; + } + + return function (exception) { + var notification = new Notification('E'); + notification.exception = exception; + notification._accept = _accept; + notification._acceptObservable = _acceptObservable; + notification.toString = toString; + return notification; + }; + }()); + + /** + * Creates an object that represents an OnCompleted notification to an observer. + * @returns {Notification} The OnCompleted notification. + */ + var notificationCreateOnCompleted = Notification.createOnCompleted = (function () { + + function _accept (onNext, onError, onCompleted) { + return onCompleted(); + } + + function _acceptObservable(observer) { + return observer.onCompleted(); + } + + function toString () { + return 'OnCompleted()'; + } + + return function () { + var notification = new Notification('C'); + notification._accept = _accept; + notification._acceptObservable = _acceptObservable; + notification.toString = toString; + return notification; + }; + }()); + + var Enumerator = Rx.internals.Enumerator = function (next) { + this._next = next; + }; + + Enumerator.prototype.next = function () { + return this._next(); + }; + + Enumerator.prototype[$iterator$] = function () { return this; } + + var Enumerable = Rx.internals.Enumerable = function (iterator) { + this._iterator = iterator; + }; + + Enumerable.prototype[$iterator$] = function () { + return this._iterator(); + }; + + Enumerable.prototype.concat = function () { + var sources = this; + return new AnonymousObservable(function (observer) { + var e; + try { + e = sources[$iterator$](); + } catch(err) { + observer.onError(); + return; + } + + var isDisposed, + subscription = new SerialDisposable(); + var cancelable = immediateScheduler.scheduleRecursive(function (self) { + var currentItem; + if (isDisposed) { return; } + + try { + currentItem = e.next(); + } catch (ex) { + observer.onError(ex); + return; + } + + if (currentItem.done) { + observer.onCompleted(); + return; + } + + // Check if promise + var currentValue = currentItem.value; + isPromise(currentValue) && (currentValue = observableFromPromise(currentValue)); + + var d = new SingleAssignmentDisposable(); + subscription.setDisposable(d); + d.setDisposable(currentValue.subscribe( + observer.onNext.bind(observer), + observer.onError.bind(observer), + function () { self(); }) + ); + }); + + return new CompositeDisposable(subscription, cancelable, disposableCreate(function () { + isDisposed = true; + })); + }); + }; + + Enumerable.prototype.catchException = function () { + var sources = this; + return new AnonymousObservable(function (observer) { + var e; + try { + e = sources[$iterator$](); + } catch(err) { + observer.onError(); + return; + } + + var isDisposed, + lastException, + subscription = new SerialDisposable(); + var cancelable = immediateScheduler.scheduleRecursive(function (self) { + if (isDisposed) { return; } + + var currentItem; + try { + currentItem = e.next(); + } catch (ex) { + observer.onError(ex); + return; + } + + if (currentItem.done) { + if (lastException) { + observer.onError(lastException); + } else { + observer.onCompleted(); + } + return; + } + + // Check if promise + var currentValue = currentItem.value; + isPromise(currentValue) && (currentValue = observableFromPromise(currentValue)); + + var d = new SingleAssignmentDisposable(); + subscription.setDisposable(d); + d.setDisposable(currentValue.subscribe( + observer.onNext.bind(observer), + function (exn) { + lastException = exn; + self(); + }, + observer.onCompleted.bind(observer))); + }); + return new CompositeDisposable(subscription, cancelable, disposableCreate(function () { + isDisposed = true; + })); + }); + }; + + var enumerableRepeat = Enumerable.repeat = function (value, repeatCount) { + if (repeatCount == null) { repeatCount = -1; } + return new Enumerable(function () { + var left = repeatCount; + return new Enumerator(function () { + if (left === 0) { return doneEnumerator; } + if (left > 0) { left--; } + return { done: false, value: value }; + }); + }); + }; + + var enumerableFor = Enumerable.forEach = function (source, selector, thisArg) { + selector || (selector = identity); + return new Enumerable(function () { + var index = -1; + return new Enumerator( + function () { + return ++index < source.length ? + { done: false, value: selector.call(thisArg, source[index], index, source) } : + doneEnumerator; + }); + }); + }; + + /** + * Supports push-style iteration over an observable sequence. + */ + var Observer = Rx.Observer = function () { }; + + /** + * Creates a notification callback from an observer. + * + * @param observer Observer object. + * @returns The action that forwards its input notification to the underlying observer. + */ + Observer.prototype.toNotifier = function () { + var observer = this; + return function (n) { + return n.accept(observer); + }; + }; + + /** + * Hides the identity of an observer. + + * @returns An observer that hides the identity of the specified observer. + */ + Observer.prototype.asObserver = function () { + return new AnonymousObserver(this.onNext.bind(this), this.onError.bind(this), this.onCompleted.bind(this)); + }; + + /** + * Checks access to the observer for grammar violations. This includes checking for multiple OnError or OnCompleted calls, as well as reentrancy in any of the observer methods. + * If a violation is detected, an Error is thrown from the offending observer method call. + * + * @returns An observer that checks callbacks invocations against the observer grammar and, if the checks pass, forwards those to the specified observer. + */ + Observer.prototype.checked = function () { return new CheckedObserver(this); }; + + /** + * Creates an observer from the specified OnNext, along with optional OnError, and OnCompleted actions. + * + * @static + * @memberOf Observer + * @param {Function} [onNext] Observer's OnNext action implementation. + * @param {Function} [onError] Observer's OnError action implementation. + * @param {Function} [onCompleted] Observer's OnCompleted action implementation. + * @returns {Observer} The observer object implemented using the given actions. + */ + var observerCreate = Observer.create = function (onNext, onError, onCompleted) { + onNext || (onNext = noop); + onError || (onError = defaultError); + onCompleted || (onCompleted = noop); + return new AnonymousObserver(onNext, onError, onCompleted); + }; + + /** + * Creates an observer from a notification callback. + * + * @static + * @memberOf Observer + * @param {Function} handler Action that handles a notification. + * @returns The observer object that invokes the specified handler using a notification corresponding to each message it receives. + */ + Observer.fromNotifier = function (handler) { + return new AnonymousObserver(function (x) { + return handler(notificationCreateOnNext(x)); + }, function (exception) { + return handler(notificationCreateOnError(exception)); + }, function () { + return handler(notificationCreateOnCompleted()); + }); + }; + + /** + * Schedules the invocation of observer methods on the given scheduler. + * @param {Scheduler} scheduler Scheduler to schedule observer messages on. + * @returns {Observer} Observer whose messages are scheduled on the given scheduler. + */ + Observer.notifyOn = function (scheduler) { + return new ObserveOnObserver(scheduler, this); + }; + + /** + * Abstract base class for implementations of the Observer class. + * This base class enforces the grammar of observers where OnError and OnCompleted are terminal messages. + */ + var AbstractObserver = Rx.internals.AbstractObserver = (function (_super) { + inherits(AbstractObserver, _super); + + /** + * Creates a new observer in a non-stopped state. + * + * @constructor + */ + function AbstractObserver() { + this.isStopped = false; + _super.call(this); + } + + /** + * Notifies the observer of a new element in the sequence. + * + * @memberOf AbstractObserver + * @param {Any} value Next element in the sequence. + */ + AbstractObserver.prototype.onNext = function (value) { + if (!this.isStopped) { + this.next(value); + } + }; + + /** + * Notifies the observer that an exception has occurred. + * + * @memberOf AbstractObserver + * @param {Any} error The error that has occurred. + */ + AbstractObserver.prototype.onError = function (error) { + if (!this.isStopped) { + this.isStopped = true; + this.error(error); + } + }; + + /** + * Notifies the observer of the end of the sequence. + */ + AbstractObserver.prototype.onCompleted = function () { + if (!this.isStopped) { + this.isStopped = true; + this.completed(); + } + }; + + /** + * Disposes the observer, causing it to transition to the stopped state. + */ + AbstractObserver.prototype.dispose = function () { + this.isStopped = true; + }; + + AbstractObserver.prototype.fail = function (e) { + if (!this.isStopped) { + this.isStopped = true; + this.error(e); + return true; + } + + return false; + }; + + return AbstractObserver; + }(Observer)); + + /** + * Class to create an Observer instance from delegate-based implementations of the on* methods. + */ + var AnonymousObserver = Rx.AnonymousObserver = (function (_super) { + inherits(AnonymousObserver, _super); + + /** + * Creates an observer from the specified OnNext, OnError, and OnCompleted actions. + * @param {Any} onNext Observer's OnNext action implementation. + * @param {Any} onError Observer's OnError action implementation. + * @param {Any} onCompleted Observer's OnCompleted action implementation. + */ + function AnonymousObserver(onNext, onError, onCompleted) { + _super.call(this); + this._onNext = onNext; + this._onError = onError; + this._onCompleted = onCompleted; + } + + /** + * Calls the onNext action. + * @param {Any} value Next element in the sequence. + */ + AnonymousObserver.prototype.next = function (value) { + this._onNext(value); + }; + + /** + * Calls the onError action. + * @param {Any} error The error that has occurred. + */ + AnonymousObserver.prototype.error = function (exception) { + this._onError(exception); + }; + + /** + * Calls the onCompleted action. + */ + AnonymousObserver.prototype.completed = function () { + this._onCompleted(); + }; + + return AnonymousObserver; + }(AbstractObserver)); + + var CheckedObserver = (function (_super) { + inherits(CheckedObserver, _super); + + function CheckedObserver(observer) { + _super.call(this); + this._observer = observer; + this._state = 0; // 0 - idle, 1 - busy, 2 - done + } + + var CheckedObserverPrototype = CheckedObserver.prototype; + + CheckedObserverPrototype.onNext = function (value) { + this.checkAccess(); + try { + this._observer.onNext(value); + } catch (e) { + throw e; + } finally { + this._state = 0; + } + }; + + CheckedObserverPrototype.onError = function (err) { + this.checkAccess(); + try { + this._observer.onError(err); + } catch (e) { + throw e; + } finally { + this._state = 2; + } + }; + + CheckedObserverPrototype.onCompleted = function () { + this.checkAccess(); + try { + this._observer.onCompleted(); + } catch (e) { + throw e; + } finally { + this._state = 2; + } + }; + + CheckedObserverPrototype.checkAccess = function () { + if (this._state === 1) { throw new Error('Re-entrancy detected'); } + if (this._state === 2) { throw new Error('Observer completed'); } + if (this._state === 0) { this._state = 1; } + }; + + return CheckedObserver; + }(Observer)); + + var ScheduledObserver = Rx.internals.ScheduledObserver = (function (_super) { + inherits(ScheduledObserver, _super); + + function ScheduledObserver(scheduler, observer) { + _super.call(this); + this.scheduler = scheduler; + this.observer = observer; + this.isAcquired = false; + this.hasFaulted = false; + this.queue = []; + this.disposable = new SerialDisposable(); + } + + ScheduledObserver.prototype.next = function (value) { + var self = this; + this.queue.push(function () { + self.observer.onNext(value); + }); + }; + + ScheduledObserver.prototype.error = function (exception) { + var self = this; + this.queue.push(function () { + self.observer.onError(exception); + }); + }; + + ScheduledObserver.prototype.completed = function () { + var self = this; + this.queue.push(function () { + self.observer.onCompleted(); + }); + }; + + ScheduledObserver.prototype.ensureActive = function () { + var isOwner = false, parent = this; + if (!this.hasFaulted && this.queue.length > 0) { + isOwner = !this.isAcquired; + this.isAcquired = true; + } + if (isOwner) { + this.disposable.setDisposable(this.scheduler.scheduleRecursive(function (self) { + var work; + if (parent.queue.length > 0) { + work = parent.queue.shift(); + } else { + parent.isAcquired = false; + return; + } + try { + work(); + } catch (ex) { + parent.queue = []; + parent.hasFaulted = true; + throw ex; + } + self(); + })); + } + }; + + ScheduledObserver.prototype.dispose = function () { + _super.prototype.dispose.call(this); + this.disposable.dispose(); + }; + + return ScheduledObserver; + }(AbstractObserver)); + + /** @private */ + var ObserveOnObserver = (function (_super) { + inherits(ObserveOnObserver, _super); + + /** @private */ + function ObserveOnObserver() { + _super.apply(this, arguments); + } + + /** @private */ + ObserveOnObserver.prototype.next = function (value) { + _super.prototype.next.call(this, value); + this.ensureActive(); + }; + + /** @private */ + ObserveOnObserver.prototype.error = function (e) { + _super.prototype.error.call(this, e); + this.ensureActive(); + }; + + /** @private */ + ObserveOnObserver.prototype.completed = function () { + _super.prototype.completed.call(this); + this.ensureActive(); + }; + + return ObserveOnObserver; + })(ScheduledObserver); + + var observableProto; + + /** + * Represents a push-style collection. + */ + var Observable = Rx.Observable = (function () { + + function Observable(subscribe) { + this._subscribe = subscribe; + } + + observableProto = Observable.prototype; + + /** + * Subscribes an observer to the observable sequence. + * + * @example + * 1 - source.subscribe(); + * 2 - source.subscribe(observer); + * 3 - source.subscribe(function (x) { console.log(x); }); + * 4 - source.subscribe(function (x) { console.log(x); }, function (err) { console.log(err); }); + * 5 - source.subscribe(function (x) { console.log(x); }, function (err) { console.log(err); }, function () { console.log('done'); }); + * @param {Mixed} [observerOrOnNext] The object that is to receive notifications or an action to invoke for each element in the observable sequence. + * @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence. + * @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence. + * @returns {Diposable} The source sequence whose subscriptions and unsubscriptions happen on the specified scheduler. + */ + observableProto.subscribe = observableProto.forEach = function (observerOrOnNext, onError, onCompleted) { + var subscriber = typeof observerOrOnNext === 'object' ? + observerOrOnNext : + observerCreate(observerOrOnNext, onError, onCompleted); + + return this._subscribe(subscriber); + }; + + return Observable; + })(); + + var AnonymousObservable = Rx.AnonymousObservable = (function (__super__) { + inherits(AnonymousObservable, __super__); + + // Fix subscriber to check for undefined or function returned to decorate as Disposable + function fixSubscriber(subscriber) { + if (typeof subscriber === 'undefined') { + subscriber = disposableEmpty; + } else if (typeof subscriber === 'function') { + subscriber = disposableCreate(subscriber); + } + + return subscriber; + } + + function AnonymousObservable(subscribe) { + if (!(this instanceof AnonymousObservable)) { + return new AnonymousObservable(subscribe); + } + + function s(observer) { + var setDisposable = function () { + try { + autoDetachObserver.setDisposable(fixSubscriber(subscribe(autoDetachObserver))); + } catch (e) { + if (!autoDetachObserver.fail(e)) { + throw e; + } + } + }; + + var autoDetachObserver = new AutoDetachObserver(observer); + if (currentThreadScheduler.scheduleRequired()) { + currentThreadScheduler.schedule(setDisposable); + } else { + setDisposable(); + } + + return autoDetachObserver; + } + + __super__.call(this, s); + } + + return AnonymousObservable; + + }(Observable)); + + /** @private */ + var AutoDetachObserver = (function (_super) { + inherits(AutoDetachObserver, _super); + + function AutoDetachObserver(observer) { + _super.call(this); + this.observer = observer; + this.m = new SingleAssignmentDisposable(); + } + + var AutoDetachObserverPrototype = AutoDetachObserver.prototype; + + AutoDetachObserverPrototype.next = function (value) { + var noError = false; + try { + this.observer.onNext(value); + noError = true; + } catch (e) { + throw e; + } finally { + if (!noError) { + this.dispose(); + } + } + }; + + AutoDetachObserverPrototype.error = function (exn) { + try { + this.observer.onError(exn); + } catch (e) { + throw e; + } finally { + this.dispose(); + } + }; + + AutoDetachObserverPrototype.completed = function () { + try { + this.observer.onCompleted(); + } catch (e) { + throw e; + } finally { + this.dispose(); + } + }; + + AutoDetachObserverPrototype.setDisposable = function (value) { this.m.setDisposable(value); }; + AutoDetachObserverPrototype.getDisposable = function (value) { return this.m.getDisposable(); }; + /* @private */ + AutoDetachObserverPrototype.disposable = function (value) { + return arguments.length ? this.getDisposable() : setDisposable(value); + }; + + AutoDetachObserverPrototype.dispose = function () { + _super.prototype.dispose.call(this); + this.m.dispose(); + }; + + return AutoDetachObserver; + }(AbstractObserver)); + + /** @private */ + var GroupedObservable = (function (_super) { + inherits(GroupedObservable, _super); + + function subscribe(observer) { + return this.underlyingObservable.subscribe(observer); + } + + /** + * @constructor + * @private + */ + function GroupedObservable(key, underlyingObservable, mergedDisposable) { + _super.call(this, subscribe); + this.key = key; + this.underlyingObservable = !mergedDisposable ? + underlyingObservable : + new AnonymousObservable(function (observer) { + return new CompositeDisposable(mergedDisposable.getDisposable(), underlyingObservable.subscribe(observer)); + }); + } + + return GroupedObservable; + }(Observable)); + + /** @private */ + var InnerSubscription = function (subject, observer) { + this.subject = subject; + this.observer = observer; + }; + + /** + * @private + * @memberOf InnerSubscription + */ + InnerSubscription.prototype.dispose = function () { + if (!this.subject.isDisposed && this.observer !== null) { + var idx = this.subject.observers.indexOf(this.observer); + this.subject.observers.splice(idx, 1); + this.observer = null; + } + }; + + /** + * Represents an object that is both an observable sequence as well as an observer. + * Each notification is broadcasted to all subscribed observers. + */ + var Subject = Rx.Subject = (function (_super) { + function subscribe(observer) { + checkDisposed.call(this); + if (!this.isStopped) { + this.observers.push(observer); + return new InnerSubscription(this, observer); + } + if (this.exception) { + observer.onError(this.exception); + return disposableEmpty; + } + observer.onCompleted(); + return disposableEmpty; + } + + inherits(Subject, _super); + + /** + * Creates a subject. + * @constructor + */ + function Subject() { + _super.call(this, subscribe); + this.isDisposed = false, + this.isStopped = false, + this.observers = []; + } + + addProperties(Subject.prototype, Observer, { + /** + * Indicates whether the subject has observers subscribed to it. + * @returns {Boolean} Indicates whether the subject has observers subscribed to it. + */ + hasObservers: function () { + return this.observers.length > 0; + }, + /** + * Notifies all subscribed observers about the end of the sequence. + */ + onCompleted: function () { + checkDisposed.call(this); + if (!this.isStopped) { + var os = this.observers.slice(0); + this.isStopped = true; + for (var i = 0, len = os.length; i < len; i++) { + os[i].onCompleted(); + } + + this.observers = []; + } + }, + /** + * Notifies all subscribed observers about the exception. + * @param {Mixed} error The exception to send to all observers. + */ + onError: function (exception) { + checkDisposed.call(this); + if (!this.isStopped) { + var os = this.observers.slice(0); + this.isStopped = true; + this.exception = exception; + for (var i = 0, len = os.length; i < len; i++) { + os[i].onError(exception); + } + + this.observers = []; + } + }, + /** + * Notifies all subscribed observers about the arrival of the specified element in the sequence. + * @param {Mixed} value The value to send to all observers. + */ + onNext: function (value) { + checkDisposed.call(this); + if (!this.isStopped) { + var os = this.observers.slice(0); + for (var i = 0, len = os.length; i < len; i++) { + os[i].onNext(value); + } + } + }, + /** + * Unsubscribe all observers and release resources. + */ + dispose: function () { + this.isDisposed = true; + this.observers = null; + } + }); + + /** + * Creates a subject from the specified observer and observable. + * @param {Observer} observer The observer used to send messages to the subject. + * @param {Observable} observable The observable used to subscribe to messages sent from the subject. + * @returns {Subject} Subject implemented using the given observer and observable. + */ + Subject.create = function (observer, observable) { + return new AnonymousSubject(observer, observable); + }; + + return Subject; + }(Observable)); + + /** + * Represents the result of an asynchronous operation. + * The last value before the OnCompleted notification, or the error received through OnError, is sent to all subscribed observers. + */ + var AsyncSubject = Rx.AsyncSubject = (function (_super) { + + function subscribe(observer) { + checkDisposed.call(this); + + if (!this.isStopped) { + this.observers.push(observer); + return new InnerSubscription(this, observer); + } + + var ex = this.exception, + hv = this.hasValue, + v = this.value; + + if (ex) { + observer.onError(ex); + } else if (hv) { + observer.onNext(v); + observer.onCompleted(); + } else { + observer.onCompleted(); + } + + return disposableEmpty; + } + + inherits(AsyncSubject, _super); + + /** + * Creates a subject that can only receive one value and that value is cached for all future observations. + * @constructor + */ + function AsyncSubject() { + _super.call(this, subscribe); + + this.isDisposed = false; + this.isStopped = false; + this.value = null; + this.hasValue = false; + this.observers = []; + this.exception = null; + } + + addProperties(AsyncSubject.prototype, Observer, { + /** + * Indicates whether the subject has observers subscribed to it. + * @returns {Boolean} Indicates whether the subject has observers subscribed to it. + */ + hasObservers: function () { + checkDisposed.call(this); + return this.observers.length > 0; + }, + /** + * Notifies all subscribed observers about the end of the sequence, also causing the last received value to be sent out (if any). + */ + onCompleted: function () { + var o, i, len; + checkDisposed.call(this); + if (!this.isStopped) { + this.isStopped = true; + var os = this.observers.slice(0), + v = this.value, + hv = this.hasValue; + + if (hv) { + for (i = 0, len = os.length; i < len; i++) { + o = os[i]; + o.onNext(v); + o.onCompleted(); + } + } else { + for (i = 0, len = os.length; i < len; i++) { + os[i].onCompleted(); + } + } + + this.observers = []; + } + }, + /** + * Notifies all subscribed observers about the exception. + * @param {Mixed} error The exception to send to all observers. + */ + onError: function (exception) { + checkDisposed.call(this); + if (!this.isStopped) { + var os = this.observers.slice(0); + this.isStopped = true; + this.exception = exception; + + for (var i = 0, len = os.length; i < len; i++) { + os[i].onError(exception); + } + + this.observers = []; + } + }, + /** + * Sends a value to the subject. The last value received before successful termination will be sent to all subscribed and future observers. + * @param {Mixed} value The value to store in the subject. + */ + onNext: function (value) { + checkDisposed.call(this); + if (!this.isStopped) { + this.value = value; + this.hasValue = true; + } + }, + /** + * Unsubscribe all observers and release resources. + */ + dispose: function () { + this.isDisposed = true; + this.observers = null; + this.exception = null; + this.value = null; + } + }); + + return AsyncSubject; + }(Observable)); + + /** @private */ + var AnonymousSubject = (function (_super) { + inherits(AnonymousSubject, _super); + + function subscribe(observer) { + return this.observable.subscribe(observer); + } + + /** + * @private + * @constructor + */ + function AnonymousSubject(observer, observable) { + _super.call(this, subscribe); + this.observer = observer; + this.observable = observable; + } + + addProperties(AnonymousSubject.prototype, Observer, { + /** + * @private + * @memberOf AnonymousSubject# + */ + onCompleted: function () { + this.observer.onCompleted(); + }, + /** + * @private + * @memberOf AnonymousSubject# + */ + onError: function (exception) { + this.observer.onError(exception); + }, + /** + * @private + * @memberOf AnonymousSubject# + */ + onNext: function (value) { + this.observer.onNext(value); + } + }); + + return AnonymousSubject; + }(Observable)); + + if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) { + root.Rx = Rx; + + define(function() { + return Rx; + }); + } else if (freeExports && freeModule) { + // in Node.js or RingoJS + if (moduleExports) { + (freeModule.exports = Rx).Rx = Rx; + } else { + freeExports.Rx = Rx; + } + } else { + // in a browser or Rhino + root.Rx = Rx; + } +}.call(this)); \ No newline at end of file diff --git a/ajax/libs/rxjs/2.2.28/rx.core.compat.min.js b/ajax/libs/rxjs/2.2.28/rx.core.compat.min.js new file mode 100644 index 000000000..94715e728 --- /dev/null +++ b/ajax/libs/rxjs/2.2.28/rx.core.compat.min.js @@ -0,0 +1 @@ +(function(t){function e(){if(this.isDisposed)throw Error(A)}function n(t){var e=typeof t;return t&&("function"==e||"object"==e)||!1}function i(t){var e=[];if(!n(t))return e;G.nonEnumArgs&&t.length&&u(t)&&(t=U.call(t));var i=G.enumPrototypes&&"function"==typeof t,r=G.enumErrorProps&&(t===H||t instanceof Error);for(var s in t)i&&"prototype"==s||r&&("message"==s||"name"==s)||e.push(s);if(G.nonEnumShadows&&t!==L){var o=t.constructor,c=-1,h=K.length;if(t===(o&&o.prototype))var a=t===stringProto?M:t===H?N:F.call(t),l=Q[a];for(;h>++c;)s=K[c],l&&l[s]||!z.call(t,s)||e.push(s)}return e}function r(t,e,n){for(var i=-1,r=n(t),s=r.length;s>++i;){var o=r[i];if(e(t[o],o,t)===!1)break}return t}function s(t,e){return r(t,e,i)}function o(t){return"function"!=typeof t.toString&&"string"==typeof(t+"")}function u(t){return t&&"object"==typeof t?F.call(t)==j:!1}function c(t){return"function"==typeof t||!1}function h(e,n,i,r){if(e===n)return 0!==e||1/e==1/n;var a=typeof e,l=typeof n;if(e===e&&(null==e||null==n||"function"!=a&&"object"!=a&&"function"!=l&&"object"!=l))return!1;var p=F.call(e),f=F.call(n);if(p==j&&(p=T),f==j&&(f=T),p!=f)return!1;switch(p){case W:case P:return+e==+n;case k:return e!=+e?n!=+n:0==e?1/e==1/n:e==+n;case I:case M:return e==n+""}var d=p==C;if(!d){if(p!=T||!G.nodeClass&&(o(e)||o(n)))return!1;var v=!G.argsObject&&u(e)?Object:e.constructor,b=!G.argsObject&&u(n)?Object:n.constructor;if(!(v==b||z.call(e,"constructor")&&z.call(n,"constructor")||c(v)&&v instanceof v&&c(b)&&b instanceof b||!("constructor"in e&&"constructor"in n)))return!1}i||(i=[]),r||(r=[]);for(var y=i.length;y--;)if(i[y]==e)return r[y]==n;var m=0;if(result=!0,i.push(e),r.push(n),d){if(y=e.length,m=n.length,result=m==y)for(;m--;){var g=n[m];if(!(result=h(e[m],g,i,r)))break}}else s(n,function(n,s,o){return z.call(o,s)?(m++,result=z.call(e,s)&&h(e[s],n,i,r)):t}),result&&s(e,function(e,n,i){return z.call(i,n)?result=--m>-1:t});return i.pop(),r.pop(),result}function a(t,e){return 1===t.length&&Array.isArray(t[e])?t[e]:U.call(t)}function l(t,e){this.scheduler=t,this.disposable=e,this.isDisposed=!1}var p={"boolean":!1,"function":!0,object:!0,number:!1,string:!1,undefined:!1},f=p[typeof window]&&window||this,d=p[typeof exports]&&exports&&!exports.nodeType&&exports,v=p[typeof module]&&module&&!module.nodeType&&module,b=v&&v.exports===d&&d,y=p[typeof global]&&global;!y||y.global!==y&&y.window!==y||(f=y);var m={internals:{},config:{Promise:f.Promise},helpers:{}},g=m.helpers.noop=function(){},w=m.helpers.identity=function(t){return t},S=(m.helpers.pluck=function(t){return function(e){return e[t]}},m.helpers.just=function(t){return function(){return t}},m.helpers.defaultNow=function(){return Date.now?Date.now:function(){return+new Date}}()),_=(m.helpers.defaultComparer=function(t,e){return J(t,e)},m.helpers.defaultSubComparer=function(t,e){return t>e?1:e>t?-1:0}),D=(m.helpers.defaultKeySerializer=function(t){return""+t},m.helpers.defaultError=function(t){throw t}),x=m.helpers.isPromise=function(t){return!!t&&"function"==typeof t.then&&t.then!==m.Observable.prototype.then};m.helpers.asArray=function(){return Array.prototype.slice.call(arguments)},m.helpers.not=function(t){return!t};var A="Object has been disposed",E="object"==typeof Symbol&&Symbol.iterator||"_es6shim_iterator_";f.Set&&"function"==typeof(new f.Set)["@@iterator"]&&(E="@@iterator");var O,R={done:!0,value:t},j="[object Arguments]",C="[object Array]",W="[object Boolean]",P="[object Date]",N="[object Error]",q="[object Function]",k="[object Number]",T="[object Object]",I="[object RegExp]",M="[object String]",F=Object.prototype.toString,z=Object.prototype.hasOwnProperty,V=F.call(arguments)==j,H=Error.prototype,L=Object.prototype,$=L.propertyIsEnumerable;try{O=!(F.call(document)==T&&!({toString:0}+""))}catch(B){O=!0}var K=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],Q={};Q[C]=Q[P]=Q[k]={constructor:!0,toLocaleString:!0,toString:!0,valueOf:!0},Q[W]=Q[M]={constructor:!0,toString:!0,valueOf:!0},Q[N]=Q[q]=Q[I]={constructor:!0,toString:!0},Q[T]={constructor:!0};var G={};(function(){var t=function(){this.x=1},e=[];t.prototype={valueOf:1,y:1};for(var n in new t)e.push(n);for(n in arguments);G.enumErrorProps=$.call(H,"message")||$.call(H,"name"),G.enumPrototypes=$.call(t,"prototype"),G.nonEnumArgs=0!=n,G.nonEnumShadows=!/valueOf/.test(e)})(1),V||(u=function(t){return t&&"object"==typeof t?z.call(t,"callee"):!1}),c(/x/)&&(c=function(t){return"function"==typeof t&&F.call(t)==q});var J=m.internals.isEqual=function(t,e){return h(t,e,[],[])},U=Array.prototype.slice;({}).hasOwnProperty;var X=this.inherits=m.internals.inherits=function(t,e){function n(){this.constructor=t}n.prototype=e.prototype,t.prototype=new n},Y=m.internals.addProperties=function(t){for(var e=U.call(arguments,1),n=0,i=e.length;i>n;n++){var r=e[n];for(var s in r)t[s]=r[s]}};m.internals.addRef=function(t,e){return new ke(function(n){return new re(e.getDisposable(),t.subscribe(n))})},Function.prototype.bind||(Function.prototype.bind=function(t){var e=this,n=U.call(arguments,1),i=function(){function r(){}if(this instanceof i){r.prototype=e.prototype;var s=new r,o=e.apply(s,n.concat(U.call(arguments)));return Object(o)===o?o:s}return e.apply(t,n.concat(U.call(arguments)))};return i});var Z=Object("a"),te="a"!=Z[0]||!(0 in Z);Array.prototype.every||(Array.prototype.every=function(t){var e=Object(this),n=te&&{}.toString.call(this)==M?this.split(""):e,i=n.length>>>0,r=arguments[1];if({}.toString.call(t)!=q)throw new TypeError(t+" is not a function");for(var s=0;i>s;s++)if(s in n&&!t.call(r,n[s],s,e))return!1;return!0}),Array.prototype.map||(Array.prototype.map=function(t){var e=Object(this),n=te&&{}.toString.call(this)==M?this.split(""):e,i=n.length>>>0,r=Array(i),s=arguments[1];if({}.toString.call(t)!=q)throw new TypeError(t+" is not a function");for(var o=0;i>o;o++)o in n&&(r[o]=t.call(s,n[o],o,e));return r}),Array.prototype.filter||(Array.prototype.filter=function(t){for(var e,n=[],i=Object(this),r=0,s=i.length>>>0;s>r;r++)e=i[r],r in i&&t.call(arguments[1],e,r,i)&&n.push(e);return n}),Array.isArray||(Array.isArray=function(t){return Object.prototype.toString.call(t)==C}),Array.prototype.indexOf||(Array.prototype.indexOf=function(t){var e=Object(this),n=e.length>>>0;if(0===n)return-1;var i=0;if(arguments.length>1&&(i=Number(arguments[1]),i!==i?i=0:0!==i&&1/0!=i&&i!==-1/0&&(i=(i>0||-1)*Math.floor(Math.abs(i)))),i>=n)return-1;for(var r=i>=0?i:Math.max(n-Math.abs(i),0);n>r;r++)if(r in e&&e[r]===t)return r;return-1});var ee=function(t,e){this.id=t,this.value=e};ee.prototype.compareTo=function(t){var e=this.value.compareTo(t.value);return 0===e&&(e=this.id-t.id),e};var ne=m.internals.PriorityQueue=function(t){this.items=Array(t),this.length=0},ie=ne.prototype;ie.isHigherPriority=function(t,e){return 0>this.items[t].compareTo(this.items[e])},ie.percolate=function(t){if(!(t>=this.length||0>t)){var e=t-1>>1;if(!(0>e||e===t)&&this.isHigherPriority(t,e)){var n=this.items[t];this.items[t]=this.items[e],this.items[e]=n,this.percolate(e)}}},ie.heapify=function(e){if(e===t&&(e=0),!(e>=this.length||0>e)){var n=2*e+1,i=2*e+2,r=e;if(this.length>n&&this.isHigherPriority(n,r)&&(r=n),this.length>i&&this.isHigherPriority(i,r)&&(r=i),r!==e){var s=this.items[e];this.items[e]=this.items[r],this.items[r]=s,this.heapify(r)}}},ie.peek=function(){return this.items[0].value},ie.removeAt=function(t){this.items[t]=this.items[--this.length],delete this.items[this.length],this.heapify()},ie.dequeue=function(){var t=this.peek();return this.removeAt(0),t},ie.enqueue=function(t){var e=this.length++;this.items[e]=new ee(ne.count++,t),this.percolate(e)},ie.remove=function(t){for(var e=0;this.length>e;e++)if(this.items[e].value===t)return this.removeAt(e),!0;return!1},ne.count=0;var re=m.CompositeDisposable=function(){this.disposables=a(arguments,0),this.isDisposed=!1,this.length=this.disposables.length},se=re.prototype;se.add=function(t){this.isDisposed?t.dispose():(this.disposables.push(t),this.length++)},se.remove=function(t){var e=!1;if(!this.isDisposed){var n=this.disposables.indexOf(t);-1!==n&&(e=!0,this.disposables.splice(n,1),this.length--,t.dispose())}return e},se.dispose=function(){if(!this.isDisposed){this.isDisposed=!0;var t=this.disposables.slice(0);this.disposables=[],this.length=0;for(var e=0,n=t.length;n>e;e++)t[e].dispose()}},se.clear=function(){var t=this.disposables.slice(0);this.disposables=[],this.length=0;for(var e=0,n=t.length;n>e;e++)t[e].dispose()},se.contains=function(t){return-1!==this.disposables.indexOf(t)},se.toArray=function(){return this.disposables.slice(0)};var oe=m.Disposable=function(t){this.isDisposed=!1,this.action=t||g};oe.prototype.dispose=function(){this.isDisposed||(this.action(),this.isDisposed=!0)};var ue=oe.create=function(t){return new oe(t)},ce=oe.empty={dispose:g},he=function(){function t(t){this.isSingle=t,this.isDisposed=!1,this.current=null}var e=t.prototype;return e.getDisposable=function(){return this.current},e.setDisposable=function(t){if(this.current&&this.isSingle)throw Error("Disposable has already been assigned");var e,n=this.isDisposed;n||(e=this.current,this.current=t),e&&e.dispose(),n&&t&&t.dispose()},e.dispose=function(){var t;this.isDisposed||(this.isDisposed=!0,t=this.current,this.current=null),t&&t.dispose()},t}(),ae=m.SingleAssignmentDisposable=function(t){function e(){t.call(this,!0)}return X(e,t),e}(he),le=m.SerialDisposable=function(t){function e(){t.call(this,!1)}return X(e,t),e}(he);m.RefCountDisposable=function(){function t(t){this.disposable=t,this.disposable.count++,this.isInnerDisposed=!1}function e(t){this.underlyingDisposable=t,this.isDisposed=!1,this.isPrimaryDisposed=!1,this.count=0}return t.prototype.dispose=function(){this.disposable.isDisposed||this.isInnerDisposed||(this.isInnerDisposed=!0,this.disposable.count--,0===this.disposable.count&&this.disposable.isPrimaryDisposed&&(this.disposable.isDisposed=!0,this.disposable.underlyingDisposable.dispose()))},e.prototype.dispose=function(){this.isDisposed||this.isPrimaryDisposed||(this.isPrimaryDisposed=!0,0===this.count&&(this.isDisposed=!0,this.underlyingDisposable.dispose()))},e.prototype.getDisposable=function(){return this.isDisposed?ce:new t(this)},e}(),l.prototype.dispose=function(){var t=this;this.scheduler.schedule(function(){t.isDisposed||(t.isDisposed=!0,t.disposable.dispose())})};var pe=m.internals.ScheduledItem=function(t,e,n,i,r){this.scheduler=t,this.state=e,this.action=n,this.dueTime=i,this.comparer=r||_,this.disposable=new ae};pe.prototype.invoke=function(){this.disposable.setDisposable(this.invokeCore())},pe.prototype.compareTo=function(t){return this.comparer(this.dueTime,t.dueTime)},pe.prototype.isCancelled=function(){return this.disposable.isDisposed},pe.prototype.invokeCore=function(){return this.action(this.scheduler,this.state)};var fe=m.Scheduler=function(){function t(t,e,n,i){this.now=t,this._schedule=e,this._scheduleRelative=n,this._scheduleAbsolute=i}function e(t,e){var n=e.first,i=e.second,r=new re,s=function(e){i(e,function(e){var n=!1,i=!1,o=t.scheduleWithState(e,function(t,e){return n?r.remove(o):i=!0,s(e),ce});i||(r.add(o),n=!0)})};return s(n),r}function n(t,e,n){var i=e.first,r=e.second,s=new re,o=function(e){r(e,function(e,i){var r=!1,u=!1,c=t[n].call(t,e,i,function(t,e){return r?s.remove(c):u=!0,o(e),ce});u||(s.add(c),r=!0)})};return o(i),s}function i(t,e){return e(),ce}var r=t.prototype;return r.catchException=r["catch"]=function(t){return new ge(this,t)},r.schedulePeriodic=function(t,e){return this.schedulePeriodicWithState(null,t,function(){e()})},r.schedulePeriodicWithState=function(t,e,n){var i=t,r=setInterval(function(){i=n(i)},e);return ue(function(){clearInterval(r)})},r.schedule=function(t){return this._schedule(t,i)},r.scheduleWithState=function(t,e){return this._schedule(t,e)},r.scheduleWithRelative=function(t,e){return this._scheduleRelative(e,t,i)},r.scheduleWithRelativeAndState=function(t,e,n){return this._scheduleRelative(t,e,n)},r.scheduleWithAbsolute=function(t,e){return this._scheduleAbsolute(e,t,i)},r.scheduleWithAbsoluteAndState=function(t,e,n){return this._scheduleAbsolute(t,e,n)},r.scheduleRecursive=function(t){return this.scheduleRecursiveWithState(t,function(t,e){t(function(){e(t)})})},r.scheduleRecursiveWithState=function(t,n){return this.scheduleWithState({first:t,second:n},function(t,n){return e(t,n)})},r.scheduleRecursiveWithRelative=function(t,e){return this.scheduleRecursiveWithRelativeAndState(e,t,function(t,e){t(function(n){e(t,n)})})},r.scheduleRecursiveWithRelativeAndState=function(t,e,i){return this._scheduleRelative({first:t,second:i},e,function(t,e){return n(t,e,"scheduleWithRelativeAndState")})},r.scheduleRecursiveWithAbsolute=function(t,e){return this.scheduleRecursiveWithAbsoluteAndState(e,t,function(t,e){t(function(n){e(t,n)})})},r.scheduleRecursiveWithAbsoluteAndState=function(t,e,i){return this._scheduleAbsolute({first:t,second:i},e,function(t,e){return n(t,e,"scheduleWithAbsoluteAndState")})},t.now=S,t.normalize=function(t){return 0>t&&(t=0),t},t}(),de=fe.normalize;m.internals.SchedulePeriodicRecursive=function(){function t(t,e){e(0,this._period);try{this._state=this._action(this._state)}catch(n){throw this._cancel.dispose(),n}}function e(t,e,n,i){this._scheduler=t,this._state=e,this._period=n,this._action=i}return e.prototype.start=function(){var e=new ae;return this._cancel=e,e.setDisposable(this._scheduler.scheduleRecursiveWithRelativeAndState(0,this._period,t.bind(this))),e},e}();var ve,be=fe.immediate=function(){function t(t,e){return e(this,t)}function e(t,e,n){for(var i=de(i);i-this.now()>0;);return n(this,t)}function n(t,e,n){return this.scheduleWithRelativeAndState(t,e-this.now(),n)}return new fe(S,t,e,n)}(),ye=fe.currentThread=function(){function t(t){for(var e;t.length>0;)if(e=t.dequeue(),!e.isCancelled()){for(;e.dueTime-fe.now()>0;);e.isCancelled()||e.invoke()}}function e(t,e){return this.scheduleWithRelativeAndState(t,0,e)}function n(e,n,i){var s=this.now()+fe.normalize(n),o=new pe(this,e,i,s);if(r)r.enqueue(o);else{r=new ne(4),r.enqueue(o);try{t(r)}catch(u){throw u}finally{r=null}}return o.disposable}function i(t,e,n){return this.scheduleWithRelativeAndState(t,e-this.now(),n)}var r,s=new fe(S,e,n,i);return s.scheduleRequired=function(){return null===r},s.ensureTrampoline=function(t){return null===r?this.schedule(t):t()},s}(),me=g;(function(){function t(){if(!f.postMessage||f.importScripts)return!1;var t=!1,e=f.onmessage;return f.onmessage=function(){t=!0},f.postMessage("","*"),f.onmessage=e,t}function e(t){if("string"==typeof t.data&&t.data.substring(0,s.length)===s){var e=t.data.substring(s.length),n=o[e];n(),delete o[e]}}var n=RegExp("^"+(F+"").replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/toString| for [^\]]+/g,".*?")+"$"),i="function"==typeof(i=y&&b&&y.setImmediate)&&!n.test(i)&&i,r="function"==typeof(r=y&&b&&y.clearImmediate)&&!n.test(r)&&r;if("undefined"!=typeof process&&"[object process]"==={}.toString.call(process))ve=process.nextTick;else if("function"==typeof i)ve=i,me=r;else if(t()){var s="ms.rx.schedule"+Math.random(),o={},u=0;f.addEventListener?f.addEventListener("message",e,!1):f.attachEvent("onmessage",e,!1),ve=function(t){var e=u++;o[e]=t,f.postMessage(s+e,"*")}}else if(f.MessageChannel){var c=new f.MessageChannel,h={},a=0;c.port1.onmessage=function(t){var e=t.data,n=h[e];n(),delete h[e]},ve=function(t){var e=a++;h[e]=t,c.port2.postMessage(e)}}else"document"in f&&"onreadystatechange"in f.document.createElement("script")?ve=function(t){var e=f.document.createElement("script");e.onreadystatechange=function(){t(),e.onreadystatechange=null,e.parentNode.removeChild(e),e=null},f.document.documentElement.appendChild(e)}:(ve=function(t){return setTimeout(t,0)},me=clearTimeout)})(),fe.timeout=function(){function t(t,e){var n=this,i=new ae,r=ve(function(){i.isDisposed||i.setDisposable(e(n,t))});return new re(i,ue(function(){me(r)}))}function e(t,e,n){var i=this,r=fe.normalize(e);if(0===r)return i.scheduleWithState(t,n);var s=new ae,o=setTimeout(function(){s.isDisposed||s.setDisposable(n(i,t))},r);return new re(s,ue(function(){clearTimeout(o)}))}function n(t,e,n){return this.scheduleWithRelativeAndState(t,e-this.now(),n)}return new fe(S,t,e,n)}();var ge=function(t){function e(){return this._scheduler.now()}function n(t,e){return this._scheduler.scheduleWithState(t,this._wrap(e))}function i(t,e,n){return this._scheduler.scheduleWithRelativeAndState(t,e,this._wrap(n))}function r(t,e,n){return this._scheduler.scheduleWithAbsoluteAndState(t,e,this._wrap(n))}function s(s,o){this._scheduler=s,this._handler=o,this._recursiveOriginal=null,this._recursiveWrapper=null,t.call(this,e,n,i,r)}return X(s,t),s.prototype._clone=function(t){return new s(t,this._handler)},s.prototype._wrap=function(t){var e=this;return function(n,i){try{return t(e._getRecursiveWrapper(n),i)}catch(r){if(!e._handler(r))throw r;return ce}}},s.prototype._getRecursiveWrapper=function(t){if(this._recursiveOriginal!==t){this._recursiveOriginal=t;var e=this._clone(t);e._recursiveOriginal=t,e._recursiveWrapper=e,this._recursiveWrapper=e}return this._recursiveWrapper},s.prototype.schedulePeriodicWithState=function(t,e,n){var i=this,r=!1,s=new ae;return s.setDisposable(this._scheduler.schedulePeriodicWithState(t,e,function(t){if(r)return null;try{return n(t)}catch(e){if(r=!0,!i._handler(e))throw e;return s.dispose(),null}})),s},s}(fe),we=m.Notification=function(){function t(t,e){this.hasValue=null==e?!1:e,this.kind=t}var e=t.prototype;return e.accept=function(t,e,n){return 1===arguments.length&&"object"==typeof t?this._acceptObservable(t):this._accept(t,e,n)},e.toObservable=function(t){var e=this;return t||(t=be),new ke(function(n){return t.schedule(function(){e._acceptObservable(n),"N"===e.kind&&n.onCompleted()})})},t}(),Se=we.createOnNext=function(){function t(t){return t(this.value)}function e(t){return t.onNext(this.value)}function n(){return"OnNext("+this.value+")"}return function(i){var r=new we("N",!0);return r.value=i,r._accept=t,r._acceptObservable=e,r.toString=n,r}}(),_e=we.createOnError=function(){function t(t,e){return e(this.exception)}function e(t){return t.onError(this.exception)}function n(){return"OnError("+this.exception+")"}return function(i){var r=new we("E");return r.exception=i,r._accept=t,r._acceptObservable=e,r.toString=n,r}}(),De=we.createOnCompleted=function(){function t(t,e,n){return n()}function e(t){return t.onCompleted()}function n(){return"OnCompleted()"}return function(){var i=new we("C");return i._accept=t,i._acceptObservable=e,i.toString=n,i}}(),xe=m.internals.Enumerator=function(t){this._next=t};xe.prototype.next=function(){return this._next()},xe.prototype[E]=function(){return this};var Ae=m.internals.Enumerable=function(t){this._iterator=t};Ae.prototype[E]=function(){return this._iterator()},Ae.prototype.concat=function(){var e=this;return new ke(function(n){var i;try{i=e[E]()}catch(r){return n.onError(),t}var s,o=new le,u=be.scheduleRecursive(function(e){var r;if(!s){try{r=i.next()}catch(u){return n.onError(u),t}if(r.done)return n.onCompleted(),t;var c=r.value;x(c)&&(c=observableFromPromise(c));var h=new ae;o.setDisposable(h),h.setDisposable(c.subscribe(n.onNext.bind(n),n.onError.bind(n),function(){e()}))}});return new re(o,u,ue(function(){s=!0}))})},Ae.prototype.catchException=function(){var e=this;return new ke(function(n){var i;try{i=e[E]()}catch(r){return n.onError(),t}var s,o,u=new le,c=be.scheduleRecursive(function(e){if(!s){var r;try{r=i.next()}catch(c){return n.onError(c),t}if(r.done)return o?n.onError(o):n.onCompleted(),t;var h=r.value;x(h)&&(h=observableFromPromise(h));var a=new ae;u.setDisposable(a),a.setDisposable(h.subscribe(n.onNext.bind(n),function(t){o=t,e()},n.onCompleted.bind(n)))}});return new re(u,c,ue(function(){s=!0}))})},Ae.repeat=function(t,e){return null==e&&(e=-1),new Ae(function(){var n=e;return new xe(function(){return 0===n?R:(n>0&&n--,{done:!1,value:t})})})},Ae.forEach=function(t,e,n){return e||(e=w),new Ae(function(){var i=-1;return new xe(function(){return++i0&&(e=!this.isAcquired,this.isAcquired=!0),e&&this.disposable.setDisposable(this.scheduler.scheduleRecursive(function(e){var i;if(!(n.queue.length>0))return n.isAcquired=!1,t;i=n.queue.shift();try{i()}catch(r){throw n.queue=[],n.hasFaulted=!0,r}e()}))},n.prototype.dispose=function(){e.prototype.dispose.call(this),this.disposable.dispose()},n}(je),Ne=function(t){function e(){t.apply(this,arguments)}return X(e,t),e.prototype.next=function(e){t.prototype.next.call(this,e),this.ensureActive()},e.prototype.error=function(e){t.prototype.error.call(this,e),this.ensureActive()},e.prototype.completed=function(){t.prototype.completed.call(this),this.ensureActive()},e}(Pe),qe=m.Observable=function(){function t(t){this._subscribe=t}return Re=t.prototype,Re.subscribe=Re.forEach=function(t,e,n){var i="object"==typeof t?t:Oe(t,e,n);return this._subscribe(i)},t}(),ke=m.AnonymousObservable=function(e){function n(e){return e===t?e=ce:"function"==typeof e&&(e=ue(e)),e}function i(r){function s(t){var e=function(){try{i.setDisposable(n(r(i)))}catch(t){if(!i.fail(t))throw t}},i=new Te(t);return ye.scheduleRequired()?ye.schedule(e):e(),i}return this instanceof i?(e.call(this,s),t):new i(r)}return X(i,e),i}(qe),Te=function(t){function e(e){t.call(this),this.observer=e,this.m=new ae}X(e,t);var n=e.prototype;return n.next=function(t){var e=!1;try{this.observer.onNext(t),e=!0}catch(n){throw n}finally{e||this.dispose()}},n.error=function(t){try{this.observer.onError(t)}catch(e){throw e}finally{this.dispose()}},n.completed=function(){try{this.observer.onCompleted()}catch(t){throw t}finally{this.dispose()}},n.setDisposable=function(t){this.m.setDisposable(t)},n.getDisposable=function(){return this.m.getDisposable()},n.disposable=function(t){return arguments.length?this.getDisposable():setDisposable(t)},n.dispose=function(){t.prototype.dispose.call(this),this.m.dispose()},e}(je);(function(t){function e(t){return this.underlyingObservable.subscribe(t)}function n(n,i,r){t.call(this,e),this.key=n,this.underlyingObservable=r?new ke(function(t){return new re(r.getDisposable(),i.subscribe(t))}):i}return X(n,t),n})(qe);var Ie=function(t,e){this.subject=t,this.observer=e};Ie.prototype.dispose=function(){if(!this.subject.isDisposed&&null!==this.observer){var t=this.subject.observers.indexOf(this.observer);this.subject.observers.splice(t,1),this.observer=null}},m.Subject=function(t){function n(t){return e.call(this),this.isStopped?this.exception?(t.onError(this.exception),ce):(t.onCompleted(),ce):(this.observers.push(t),new Ie(this,t))}function i(){t.call(this,n),this.isDisposed=!1,this.isStopped=!1,this.observers=[]}return X(i,t),Y(i.prototype,Ee,{hasObservers:function(){return this.observers.length>0},onCompleted:function(){if(e.call(this),!this.isStopped){var t=this.observers.slice(0);this.isStopped=!0;for(var n=0,i=t.length;i>n;n++)t[n].onCompleted();this.observers=[]}},onError:function(t){if(e.call(this),!this.isStopped){var n=this.observers.slice(0);this.isStopped=!0,this.exception=t;for(var i=0,r=n.length;r>i;i++)n[i].onError(t);this.observers=[]}},onNext:function(t){if(e.call(this),!this.isStopped)for(var n=this.observers.slice(0),i=0,r=n.length;r>i;i++)n[i].onNext(t)},dispose:function(){this.isDisposed=!0,this.observers=null}}),i.create=function(t,e){return new Me(t,e)},i}(qe),m.AsyncSubject=function(t){function n(t){if(e.call(this),!this.isStopped)return this.observers.push(t),new Ie(this,t);var n=this.exception,i=this.hasValue,r=this.value;return n?t.onError(n):i?(t.onNext(r),t.onCompleted()):t.onCompleted(),ce}function i(){t.call(this,n),this.isDisposed=!1,this.isStopped=!1,this.value=null,this.hasValue=!1,this.observers=[],this.exception=null}return X(i,t),Y(i.prototype,Ee,{hasObservers:function(){return e.call(this),this.observers.length>0},onCompleted:function(){var t,n,i;if(e.call(this),!this.isStopped){this.isStopped=!0;var r=this.observers.slice(0),s=this.value,o=this.hasValue;if(o)for(n=0,i=r.length;i>n;n++)t=r[n],t.onNext(s),t.onCompleted();else for(n=0,i=r.length;i>n;n++)r[n].onCompleted();this.observers=[]}},onError:function(t){if(e.call(this),!this.isStopped){var n=this.observers.slice(0);this.isStopped=!0,this.exception=t;for(var i=0,r=n.length;r>i;i++)n[i].onError(t);this.observers=[]}},onNext:function(t){e.call(this),this.isStopped||(this.value=t,this.hasValue=!0)},dispose:function(){this.isDisposed=!0,this.observers=null,this.exception=null,this.value=null}}),i}(qe);var Me=function(t){function e(t){return this.observable.subscribe(t)}function n(n,i){t.call(this,e),this.observer=n,this.observable=i}return X(n,t),Y(n.prototype,Ee,{onCompleted:function(){this.observer.onCompleted()},onError:function(t){this.observer.onError(t)},onNext:function(t){this.observer.onNext(t)}}),n}(qe);"function"==typeof define&&"object"==typeof define.amd&&define.amd?(f.Rx=m,define(function(){return m})):d&&v?b?(v.exports=m).Rx=m:d.Rx=m:f.Rx=m}).call(this); \ No newline at end of file diff --git a/ajax/libs/rxjs/2.2.28/rx.core.js b/ajax/libs/rxjs/2.2.28/rx.core.js new file mode 100644 index 000000000..df16664d2 --- /dev/null +++ b/ajax/libs/rxjs/2.2.28/rx.core.js @@ -0,0 +1,2509 @@ +// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. + +;(function (undefined) { + + var objectTypes = { + 'boolean': false, + 'function': true, + 'object': true, + 'number': false, + 'string': false, + 'undefined': false + }; + + var root = (objectTypes[typeof window] && window) || this, + freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports, + freeModule = objectTypes[typeof module] && module && !module.nodeType && module, + moduleExports = freeModule && freeModule.exports === freeExports && freeExports, + freeGlobal = objectTypes[typeof global] && global; + + if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal)) { + root = freeGlobal; + } + + var Rx = { + internals: {}, + config: { + Promise: root.Promise // Detect if promise exists + }, + helpers: { } + }; + + // Defaults + var noop = Rx.helpers.noop = function () { }, + identity = Rx.helpers.identity = function (x) { return x; }, + pluck = Rx.helpers.pluck = function (property) { return function (x) { return x[property]; }; }, + just = Rx.helpers.just = function (value) { return function () { return value; }; }, + defaultNow = Rx.helpers.defaultNow = Date.now, + defaultComparer = Rx.helpers.defaultComparer = function (x, y) { return isEqual(x, y); }, + defaultSubComparer = Rx.helpers.defaultSubComparer = function (x, y) { return x > y ? 1 : (x < y ? -1 : 0); }, + defaultKeySerializer = Rx.helpers.defaultKeySerializer = function (x) { return x.toString(); }, + defaultError = Rx.helpers.defaultError = function (err) { throw err; }, + isPromise = Rx.helpers.isPromise = function (p) { return !!p && typeof p.then === 'function' && p.then !== Rx.Observable.prototype.then; }, + asArray = Rx.helpers.asArray = function () { return Array.prototype.slice.call(arguments); }, + not = Rx.helpers.not = function (a) { return !a; }; + + // Errors + var sequenceContainsNoElements = 'Sequence contains no elements.'; + var argumentOutOfRange = 'Argument out of range'; + var objectDisposed = 'Object has been disposed'; + function checkDisposed() { if (this.isDisposed) { throw new Error(objectDisposed); } } + + // Shim in iterator support + var $iterator$ = (typeof Symbol === 'object' && Symbol.iterator) || + '_es6shim_iterator_'; + // Firefox ships a partial implementation using the name @@iterator. + // https://bugzilla.mozilla.org/show_bug.cgi?id=907077#c14 + // So use that name if we detect it. + if (root.Set && typeof new root.Set()['@@iterator'] === 'function') { + $iterator$ = '@@iterator'; + } + var doneEnumerator = { done: true, value: undefined }; + + /** `Object#toString` result shortcuts */ + var argsClass = '[object Arguments]', + arrayClass = '[object Array]', + boolClass = '[object Boolean]', + dateClass = '[object Date]', + errorClass = '[object Error]', + funcClass = '[object Function]', + numberClass = '[object Number]', + objectClass = '[object Object]', + regexpClass = '[object RegExp]', + stringClass = '[object String]'; + + var toString = Object.prototype.toString, + hasOwnProperty = Object.prototype.hasOwnProperty, + supportsArgsClass = toString.call(arguments) == argsClass, // For less -1); + } + }); + } + } + stackA.pop(); + stackB.pop(); + + return result; + } + var slice = Array.prototype.slice; + function argsOrArray(args, idx) { + return args.length === 1 && Array.isArray(args[idx]) ? + args[idx] : + slice.call(args); + } + var hasProp = {}.hasOwnProperty; + + /** @private */ + var inherits = this.inherits = Rx.internals.inherits = function (child, parent) { + function __() { this.constructor = child; } + __.prototype = parent.prototype; + child.prototype = new __(); + }; + + /** @private */ + var addProperties = Rx.internals.addProperties = function (obj) { + var sources = slice.call(arguments, 1); + for (var i = 0, len = sources.length; i < len; i++) { + var source = sources[i]; + for (var prop in source) { + obj[prop] = source[prop]; + } + } + }; + + // Rx Utils + var addRef = Rx.internals.addRef = function (xs, r) { + return new AnonymousObservable(function (observer) { + return new CompositeDisposable(r.getDisposable(), xs.subscribe(observer)); + }); + }; + + // Collection polyfills + function arrayInitialize(count, factory) { + var a = new Array(count); + for (var i = 0; i < count; i++) { + a[i] = factory(); + } + return a; + } + + // Collections + var IndexedItem = function (id, value) { + this.id = id; + this.value = value; + }; + + IndexedItem.prototype.compareTo = function (other) { + var c = this.value.compareTo(other.value); + if (c === 0) { + c = this.id - other.id; + } + return c; + }; + + // Priority Queue for Scheduling + var PriorityQueue = Rx.internals.PriorityQueue = function (capacity) { + this.items = new Array(capacity); + this.length = 0; + }; + + var priorityProto = PriorityQueue.prototype; + priorityProto.isHigherPriority = function (left, right) { + return this.items[left].compareTo(this.items[right]) < 0; + }; + + priorityProto.percolate = function (index) { + if (index >= this.length || index < 0) { + return; + } + var parent = index - 1 >> 1; + if (parent < 0 || parent === index) { + return; + } + if (this.isHigherPriority(index, parent)) { + var temp = this.items[index]; + this.items[index] = this.items[parent]; + this.items[parent] = temp; + this.percolate(parent); + } + }; + + priorityProto.heapify = function (index) { + if (index === undefined) { + index = 0; + } + if (index >= this.length || index < 0) { + return; + } + var left = 2 * index + 1, + right = 2 * index + 2, + first = index; + if (left < this.length && this.isHigherPriority(left, first)) { + first = left; + } + if (right < this.length && this.isHigherPriority(right, first)) { + first = right; + } + if (first !== index) { + var temp = this.items[index]; + this.items[index] = this.items[first]; + this.items[first] = temp; + this.heapify(first); + } + }; + + priorityProto.peek = function () { return this.items[0].value; }; + + priorityProto.removeAt = function (index) { + this.items[index] = this.items[--this.length]; + delete this.items[this.length]; + this.heapify(); + }; + + priorityProto.dequeue = function () { + var result = this.peek(); + this.removeAt(0); + return result; + }; + + priorityProto.enqueue = function (item) { + var index = this.length++; + this.items[index] = new IndexedItem(PriorityQueue.count++, item); + this.percolate(index); + }; + + priorityProto.remove = function (item) { + for (var i = 0; i < this.length; i++) { + if (this.items[i].value === item) { + this.removeAt(i); + return true; + } + } + return false; + }; + PriorityQueue.count = 0; + /** + * Represents a group of disposable resources that are disposed together. + * @constructor + */ + var CompositeDisposable = Rx.CompositeDisposable = function () { + this.disposables = argsOrArray(arguments, 0); + this.isDisposed = false; + this.length = this.disposables.length; + }; + + var CompositeDisposablePrototype = CompositeDisposable.prototype; + + /** + * Adds a disposable to the CompositeDisposable or disposes the disposable if the CompositeDisposable is disposed. + * @param {Mixed} item Disposable to add. + */ + CompositeDisposablePrototype.add = function (item) { + if (this.isDisposed) { + item.dispose(); + } else { + this.disposables.push(item); + this.length++; + } + }; + + /** + * Removes and disposes the first occurrence of a disposable from the CompositeDisposable. + * @param {Mixed} item Disposable to remove. + * @returns {Boolean} true if found; false otherwise. + */ + CompositeDisposablePrototype.remove = function (item) { + var shouldDispose = false; + if (!this.isDisposed) { + var idx = this.disposables.indexOf(item); + if (idx !== -1) { + shouldDispose = true; + this.disposables.splice(idx, 1); + this.length--; + item.dispose(); + } + + } + return shouldDispose; + }; + + /** + * Disposes all disposables in the group and removes them from the group. + */ + CompositeDisposablePrototype.dispose = function () { + if (!this.isDisposed) { + this.isDisposed = true; + var currentDisposables = this.disposables.slice(0); + this.disposables = []; + this.length = 0; + + for (var i = 0, len = currentDisposables.length; i < len; i++) { + currentDisposables[i].dispose(); + } + } + }; + + /** + * Removes and disposes all disposables from the CompositeDisposable, but does not dispose the CompositeDisposable. + */ + CompositeDisposablePrototype.clear = function () { + var currentDisposables = this.disposables.slice(0); + this.disposables = []; + this.length = 0; + for (var i = 0, len = currentDisposables.length; i < len; i++) { + currentDisposables[i].dispose(); + } + }; + + /** + * Determines whether the CompositeDisposable contains a specific disposable. + * @param {Mixed} item Disposable to search for. + * @returns {Boolean} true if the disposable was found; otherwise, false. + */ + CompositeDisposablePrototype.contains = function (item) { + return this.disposables.indexOf(item) !== -1; + }; + + /** + * Converts the existing CompositeDisposable to an array of disposables + * @returns {Array} An array of disposable objects. + */ + CompositeDisposablePrototype.toArray = function () { + return this.disposables.slice(0); + }; + + /** + * Provides a set of static methods for creating Disposables. + * + * @constructor + * @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once. + */ + var Disposable = Rx.Disposable = function (action) { + this.isDisposed = false; + this.action = action || noop; + }; + + /** Performs the task of cleaning up resources. */ + Disposable.prototype.dispose = function () { + if (!this.isDisposed) { + this.action(); + this.isDisposed = true; + } + }; + + /** + * Creates a disposable object that invokes the specified action when disposed. + * @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once. + * @return {Disposable} The disposable object that runs the given action upon disposal. + */ + var disposableCreate = Disposable.create = function (action) { return new Disposable(action); }; + + /** + * Gets the disposable that does nothing when disposed. + */ + var disposableEmpty = Disposable.empty = { dispose: noop }; + + var BooleanDisposable = (function () { + function BooleanDisposable (isSingle) { + this.isSingle = isSingle; + this.isDisposed = false; + this.current = null; + } + + var booleanDisposablePrototype = BooleanDisposable.prototype; + + /** + * Gets the underlying disposable. + * @return The underlying disposable. + */ + booleanDisposablePrototype.getDisposable = function () { + return this.current; + }; + + /** + * Sets the underlying disposable. + * @param {Disposable} value The new underlying disposable. + */ + booleanDisposablePrototype.setDisposable = function (value) { + if (this.current && this.isSingle) { + throw new Error('Disposable has already been assigned'); + } + + var shouldDispose = this.isDisposed, old; + if (!shouldDispose) { + old = this.current; + this.current = value; + } + if (old) { + old.dispose(); + } + if (shouldDispose && value) { + value.dispose(); + } + }; + + /** + * Disposes the underlying disposable as well as all future replacements. + */ + booleanDisposablePrototype.dispose = function () { + var old; + if (!this.isDisposed) { + this.isDisposed = true; + old = this.current; + this.current = null; + } + if (old) { + old.dispose(); + } + }; + + return BooleanDisposable; + }()); + + /** + * Represents a disposable resource which only allows a single assignment of its underlying disposable resource. + * If an underlying disposable resource has already been set, future attempts to set the underlying disposable resource will throw an Error. + */ + var SingleAssignmentDisposable = Rx.SingleAssignmentDisposable = (function (super_) { + inherits(SingleAssignmentDisposable, super_); + + function SingleAssignmentDisposable() { + super_.call(this, true); + } + + return SingleAssignmentDisposable; + }(BooleanDisposable)); + + /** + * Represents a disposable resource whose underlying disposable resource can be replaced by another disposable resource, causing automatic disposal of the previous underlying disposable resource. + */ + var SerialDisposable = Rx.SerialDisposable = (function (super_) { + inherits(SerialDisposable, super_); + + function SerialDisposable() { + super_.call(this, false); + } + + return SerialDisposable; + }(BooleanDisposable)); + + /** + * Represents a disposable resource that only disposes its underlying disposable resource when all dependent disposable objects have been disposed. + */ + var RefCountDisposable = Rx.RefCountDisposable = (function () { + + function InnerDisposable(disposable) { + this.disposable = disposable; + this.disposable.count++; + this.isInnerDisposed = false; + } + + InnerDisposable.prototype.dispose = function () { + if (!this.disposable.isDisposed) { + if (!this.isInnerDisposed) { + this.isInnerDisposed = true; + this.disposable.count--; + if (this.disposable.count === 0 && this.disposable.isPrimaryDisposed) { + this.disposable.isDisposed = true; + this.disposable.underlyingDisposable.dispose(); + } + } + } + }; + + /** + * Initializes a new instance of the RefCountDisposable with the specified disposable. + * @constructor + * @param {Disposable} disposable Underlying disposable. + */ + function RefCountDisposable(disposable) { + this.underlyingDisposable = disposable; + this.isDisposed = false; + this.isPrimaryDisposed = false; + this.count = 0; + } + + /** + * Disposes the underlying disposable only when all dependent disposables have been disposed + */ + RefCountDisposable.prototype.dispose = function () { + if (!this.isDisposed) { + if (!this.isPrimaryDisposed) { + this.isPrimaryDisposed = true; + if (this.count === 0) { + this.isDisposed = true; + this.underlyingDisposable.dispose(); + } + } + } + }; + + /** + * Returns a dependent disposable that when disposed decreases the refcount on the underlying disposable. + * @returns {Disposable} A dependent disposable contributing to the reference count that manages the underlying disposable's lifetime. + */ + RefCountDisposable.prototype.getDisposable = function () { + return this.isDisposed ? disposableEmpty : new InnerDisposable(this); + }; + + return RefCountDisposable; + })(); + + function ScheduledDisposable(scheduler, disposable) { + this.scheduler = scheduler; + this.disposable = disposable; + this.isDisposed = false; + } + + ScheduledDisposable.prototype.dispose = function () { + var parent = this; + this.scheduler.schedule(function () { + if (!parent.isDisposed) { + parent.isDisposed = true; + parent.disposable.dispose(); + } + }); + }; + + var ScheduledItem = Rx.internals.ScheduledItem = function (scheduler, state, action, dueTime, comparer) { + this.scheduler = scheduler; + this.state = state; + this.action = action; + this.dueTime = dueTime; + this.comparer = comparer || defaultSubComparer; + this.disposable = new SingleAssignmentDisposable(); + } + + ScheduledItem.prototype.invoke = function () { + this.disposable.setDisposable(this.invokeCore()); + }; + + ScheduledItem.prototype.compareTo = function (other) { + return this.comparer(this.dueTime, other.dueTime); + }; + + ScheduledItem.prototype.isCancelled = function () { + return this.disposable.isDisposed; + }; + + ScheduledItem.prototype.invokeCore = function () { + return this.action(this.scheduler, this.state); + }; + + /** Provides a set of static properties to access commonly used schedulers. */ + var Scheduler = Rx.Scheduler = (function () { + + /** + * @constructor + * @private + */ + function Scheduler(now, schedule, scheduleRelative, scheduleAbsolute) { + this.now = now; + this._schedule = schedule; + this._scheduleRelative = scheduleRelative; + this._scheduleAbsolute = scheduleAbsolute; + } + + function invokeRecImmediate(scheduler, pair) { + var state = pair.first, action = pair.second, group = new CompositeDisposable(), + recursiveAction = function (state1) { + action(state1, function (state2) { + var isAdded = false, isDone = false, + d = scheduler.scheduleWithState(state2, function (scheduler1, state3) { + if (isAdded) { + group.remove(d); + } else { + isDone = true; + } + recursiveAction(state3); + return disposableEmpty; + }); + if (!isDone) { + group.add(d); + isAdded = true; + } + }); + }; + recursiveAction(state); + return group; + } + + function invokeRecDate(scheduler, pair, method) { + var state = pair.first, action = pair.second, group = new CompositeDisposable(), + recursiveAction = function (state1) { + action(state1, function (state2, dueTime1) { + var isAdded = false, isDone = false, + d = scheduler[method].call(scheduler, state2, dueTime1, function (scheduler1, state3) { + if (isAdded) { + group.remove(d); + } else { + isDone = true; + } + recursiveAction(state3); + return disposableEmpty; + }); + if (!isDone) { + group.add(d); + isAdded = true; + } + }); + }; + recursiveAction(state); + return group; + } + + function invokeAction(scheduler, action) { + action(); + return disposableEmpty; + } + + var schedulerProto = Scheduler.prototype; + + /** + * Returns a scheduler that wraps the original scheduler, adding exception handling for scheduled actions. + * @param {Function} handler Handler that's run if an exception is caught. The exception will be rethrown if the handler returns false. + * @returns {Scheduler} Wrapper around the original scheduler, enforcing exception handling. + */ + schedulerProto.catchException = schedulerProto['catch'] = function (handler) { + return new CatchScheduler(this, handler); + }; + + /** + * Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation. + * @param {Number} period Period for running the work periodically. + * @param {Function} action Action to be executed. + * @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort). + */ + schedulerProto.schedulePeriodic = function (period, action) { + return this.schedulePeriodicWithState(null, period, function () { + action(); + }); + }; + + /** + * Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation. + * @param {Mixed} state Initial state passed to the action upon the first iteration. + * @param {Number} period Period for running the work periodically. + * @param {Function} action Action to be executed, potentially updating the state. + * @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort). + */ + schedulerProto.schedulePeriodicWithState = function (state, period, action) { + var s = state, id = setInterval(function () { + s = action(s); + }, period); + return disposableCreate(function () { + clearInterval(id); + }); + }; + + /** + * Schedules an action to be executed. + * @param {Function} action Action to execute. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.schedule = function (action) { + return this._schedule(action, invokeAction); + }; + + /** + * Schedules an action to be executed. + * @param state State passed to the action to be executed. + * @param {Function} action Action to be executed. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleWithState = function (state, action) { + return this._schedule(state, action); + }; + + /** + * Schedules an action to be executed after the specified relative due time. + * @param {Function} action Action to execute. + * @param {Number} dueTime Relative time after which to execute the action. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleWithRelative = function (dueTime, action) { + return this._scheduleRelative(action, dueTime, invokeAction); + }; + + /** + * Schedules an action to be executed after dueTime. + * @param state State passed to the action to be executed. + * @param {Function} action Action to be executed. + * @param {Number} dueTime Relative time after which to execute the action. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleWithRelativeAndState = function (state, dueTime, action) { + return this._scheduleRelative(state, dueTime, action); + }; + + /** + * Schedules an action to be executed at the specified absolute due time. + * @param {Function} action Action to execute. + * @param {Number} dueTime Absolute time at which to execute the action. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleWithAbsolute = function (dueTime, action) { + return this._scheduleAbsolute(action, dueTime, invokeAction); + }; + + /** + * Schedules an action to be executed at dueTime. + * @param {Mixed} state State passed to the action to be executed. + * @param {Function} action Action to be executed. + * @param {Number}dueTime Absolute time at which to execute the action. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleWithAbsoluteAndState = function (state, dueTime, action) { + return this._scheduleAbsolute(state, dueTime, action); + }; + + /** + * Schedules an action to be executed recursively. + * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleRecursive = function (action) { + return this.scheduleRecursiveWithState(action, function (_action, self) { + _action(function () { + self(_action); + }); + }); + }; + + /** + * Schedules an action to be executed recursively. + * @param {Mixed} state State passed to the action to be executed. + * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in recursive invocation state. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleRecursiveWithState = function (state, action) { + return this.scheduleWithState({ first: state, second: action }, function (s, p) { + return invokeRecImmediate(s, p); + }); + }; + + /** + * Schedules an action to be executed recursively after a specified relative due time. + * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified relative time. + * @param {Number}dueTime Relative time after which to execute the action for the first time. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleRecursiveWithRelative = function (dueTime, action) { + return this.scheduleRecursiveWithRelativeAndState(action, dueTime, function (_action, self) { + _action(function (dt) { + self(_action, dt); + }); + }); + }; + + /** + * Schedules an action to be executed recursively after a specified relative due time. + * @param {Mixed} state State passed to the action to be executed. + * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state. + * @param {Number}dueTime Relative time after which to execute the action for the first time. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleRecursiveWithRelativeAndState = function (state, dueTime, action) { + return this._scheduleRelative({ first: state, second: action }, dueTime, function (s, p) { + return invokeRecDate(s, p, 'scheduleWithRelativeAndState'); + }); + }; + + /** + * Schedules an action to be executed recursively at a specified absolute due time. + * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified absolute time. + * @param {Number}dueTime Absolute time at which to execute the action for the first time. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleRecursiveWithAbsolute = function (dueTime, action) { + return this.scheduleRecursiveWithAbsoluteAndState(action, dueTime, function (_action, self) { + _action(function (dt) { + self(_action, dt); + }); + }); + }; + + /** + * Schedules an action to be executed recursively at a specified absolute due time. + * @param {Mixed} state State passed to the action to be executed. + * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state. + * @param {Number}dueTime Absolute time at which to execute the action for the first time. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleRecursiveWithAbsoluteAndState = function (state, dueTime, action) { + return this._scheduleAbsolute({ first: state, second: action }, dueTime, function (s, p) { + return invokeRecDate(s, p, 'scheduleWithAbsoluteAndState'); + }); + }; + + /** Gets the current time according to the local machine's system clock. */ + Scheduler.now = defaultNow; + + /** + * Normalizes the specified TimeSpan value to a positive value. + * @param {Number} timeSpan The time span value to normalize. + * @returns {Number} The specified TimeSpan value if it is zero or positive; otherwise, 0 + */ + Scheduler.normalize = function (timeSpan) { + if (timeSpan < 0) { + timeSpan = 0; + } + return timeSpan; + }; + + return Scheduler; + }()); + + var normalizeTime = Scheduler.normalize; + + var SchedulePeriodicRecursive = Rx.internals.SchedulePeriodicRecursive = (function () { + function tick(command, recurse) { + recurse(0, this._period); + try { + this._state = this._action(this._state); + } catch (e) { + this._cancel.dispose(); + throw e; + } + } + + function SchedulePeriodicRecursive(scheduler, state, period, action) { + this._scheduler = scheduler; + this._state = state; + this._period = period; + this._action = action; + } + + SchedulePeriodicRecursive.prototype.start = function () { + var d = new SingleAssignmentDisposable(); + this._cancel = d; + d.setDisposable(this._scheduler.scheduleRecursiveWithRelativeAndState(0, this._period, tick.bind(this))); + + return d; + }; + + return SchedulePeriodicRecursive; + }()); + + /** + * Gets a scheduler that schedules work immediately on the current thread. + */ + var immediateScheduler = Scheduler.immediate = (function () { + + function scheduleNow(state, action) { return action(this, state); } + + function scheduleRelative(state, dueTime, action) { + var dt = normalizeTime(dt); + while (dt - this.now() > 0) { } + return action(this, state); + } + + function scheduleAbsolute(state, dueTime, action) { + return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); + } + + return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); + }()); + + /** + * Gets a scheduler that schedules work as soon as possible on the current thread. + */ + var currentThreadScheduler = Scheduler.currentThread = (function () { + var queue; + + function runTrampoline (q) { + var item; + while (q.length > 0) { + item = q.dequeue(); + if (!item.isCancelled()) { + // Note, do not schedule blocking work! + while (item.dueTime - Scheduler.now() > 0) { + } + if (!item.isCancelled()) { + item.invoke(); + } + } + } + } + + function scheduleNow(state, action) { + return this.scheduleWithRelativeAndState(state, 0, action); + } + + function scheduleRelative(state, dueTime, action) { + var dt = this.now() + Scheduler.normalize(dueTime), + si = new ScheduledItem(this, state, action, dt), + t; + if (!queue) { + queue = new PriorityQueue(4); + queue.enqueue(si); + try { + runTrampoline(queue); + } catch (e) { + throw e; + } finally { + queue = null; + } + } else { + queue.enqueue(si); + } + return si.disposable; + } + + function scheduleAbsolute(state, dueTime, action) { + return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); + } + + var currentScheduler = new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); + currentScheduler.scheduleRequired = function () { return queue === null; }; + currentScheduler.ensureTrampoline = function (action) { + if (queue === null) { + return this.schedule(action); + } else { + return action(); + } + }; + + return currentScheduler; + }()); + + + var scheduleMethod, clearMethod = noop; + (function () { + + var reNative = RegExp('^' + + String(toString) + .replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + .replace(/toString| for [^\]]+/g, '.*?') + '$' + ); + + var setImmediate = typeof (setImmediate = freeGlobal && moduleExports && freeGlobal.setImmediate) == 'function' && + !reNative.test(setImmediate) && setImmediate, + clearImmediate = typeof (clearImmediate = freeGlobal && moduleExports && freeGlobal.clearImmediate) == 'function' && + !reNative.test(clearImmediate) && clearImmediate; + + function postMessageSupported () { + // Ensure not in a worker + if (!root.postMessage || root.importScripts) { return false; } + var isAsync = false, + oldHandler = root.onmessage; + // Test for async + root.onmessage = function () { isAsync = true; }; + root.postMessage('','*'); + root.onmessage = oldHandler; + + return isAsync; + } + + // Use in order, nextTick, setImmediate, postMessage, MessageChannel, script readystatechanged, setTimeout + if (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]') { + scheduleMethod = process.nextTick; + } else if (typeof setImmediate === 'function') { + scheduleMethod = setImmediate; + clearMethod = clearImmediate; + } else if (postMessageSupported()) { + var MSG_PREFIX = 'ms.rx.schedule' + Math.random(), + tasks = {}, + taskId = 0; + + function onGlobalPostMessage(event) { + // Only if we're a match to avoid any other global events + if (typeof event.data === 'string' && event.data.substring(0, MSG_PREFIX.length) === MSG_PREFIX) { + var handleId = event.data.substring(MSG_PREFIX.length), + action = tasks[handleId]; + action(); + delete tasks[handleId]; + } + } + + if (root.addEventListener) { + root.addEventListener('message', onGlobalPostMessage, false); + } else { + root.attachEvent('onmessage', onGlobalPostMessage, false); + } + + scheduleMethod = function (action) { + var currentId = taskId++; + tasks[currentId] = action; + root.postMessage(MSG_PREFIX + currentId, '*'); + }; + } else if (!!root.MessageChannel) { + var channel = new root.MessageChannel(), + channelTasks = {}, + channelTaskId = 0; + + channel.port1.onmessage = function (event) { + var id = event.data, + action = channelTasks[id]; + action(); + delete channelTasks[id]; + }; + + scheduleMethod = function (action) { + var id = channelTaskId++; + channelTasks[id] = action; + channel.port2.postMessage(id); + }; + } else if ('document' in root && 'onreadystatechange' in root.document.createElement('script')) { + + scheduleMethod = function (action) { + var scriptElement = root.document.createElement('script'); + scriptElement.onreadystatechange = function () { + action(); + scriptElement.onreadystatechange = null; + scriptElement.parentNode.removeChild(scriptElement); + scriptElement = null; + }; + root.document.documentElement.appendChild(scriptElement); + }; + + } else { + scheduleMethod = function (action) { return setTimeout(action, 0); }; + clearMethod = clearTimeout; + } + }()); + + /** + * Gets a scheduler that schedules work via a timed callback based upon platform. + */ + var timeoutScheduler = Scheduler.timeout = (function () { + + function scheduleNow(state, action) { + var scheduler = this, + disposable = new SingleAssignmentDisposable(); + var id = scheduleMethod(function () { + if (!disposable.isDisposed) { + disposable.setDisposable(action(scheduler, state)); + } + }); + return new CompositeDisposable(disposable, disposableCreate(function () { + clearMethod(id); + })); + } + + function scheduleRelative(state, dueTime, action) { + var scheduler = this, + dt = Scheduler.normalize(dueTime); + if (dt === 0) { + return scheduler.scheduleWithState(state, action); + } + var disposable = new SingleAssignmentDisposable(); + var id = setTimeout(function () { + if (!disposable.isDisposed) { + disposable.setDisposable(action(scheduler, state)); + } + }, dt); + return new CompositeDisposable(disposable, disposableCreate(function () { + clearTimeout(id); + })); + } + + function scheduleAbsolute(state, dueTime, action) { + return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); + } + + return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); + })(); + + /** @private */ + var CatchScheduler = (function (_super) { + + function localNow() { + return this._scheduler.now(); + } + + function scheduleNow(state, action) { + return this._scheduler.scheduleWithState(state, this._wrap(action)); + } + + function scheduleRelative(state, dueTime, action) { + return this._scheduler.scheduleWithRelativeAndState(state, dueTime, this._wrap(action)); + } + + function scheduleAbsolute(state, dueTime, action) { + return this._scheduler.scheduleWithAbsoluteAndState(state, dueTime, this._wrap(action)); + } + + inherits(CatchScheduler, _super); + + /** @private */ + function CatchScheduler(scheduler, handler) { + this._scheduler = scheduler; + this._handler = handler; + this._recursiveOriginal = null; + this._recursiveWrapper = null; + _super.call(this, localNow, scheduleNow, scheduleRelative, scheduleAbsolute); + } + + /** @private */ + CatchScheduler.prototype._clone = function (scheduler) { + return new CatchScheduler(scheduler, this._handler); + }; + + /** @private */ + CatchScheduler.prototype._wrap = function (action) { + var parent = this; + return function (self, state) { + try { + return action(parent._getRecursiveWrapper(self), state); + } catch (e) { + if (!parent._handler(e)) { throw e; } + return disposableEmpty; + } + }; + }; + + /** @private */ + CatchScheduler.prototype._getRecursiveWrapper = function (scheduler) { + if (this._recursiveOriginal !== scheduler) { + this._recursiveOriginal = scheduler; + var wrapper = this._clone(scheduler); + wrapper._recursiveOriginal = scheduler; + wrapper._recursiveWrapper = wrapper; + this._recursiveWrapper = wrapper; + } + return this._recursiveWrapper; + }; + + /** @private */ + CatchScheduler.prototype.schedulePeriodicWithState = function (state, period, action) { + var self = this, failed = false, d = new SingleAssignmentDisposable(); + + d.setDisposable(this._scheduler.schedulePeriodicWithState(state, period, function (state1) { + if (failed) { return null; } + try { + return action(state1); + } catch (e) { + failed = true; + if (!self._handler(e)) { throw e; } + d.dispose(); + return null; + } + })); + + return d; + }; + + return CatchScheduler; + }(Scheduler)); + + /** + * Represents a notification to an observer. + */ + var Notification = Rx.Notification = (function () { + function Notification(kind, hasValue) { + this.hasValue = hasValue == null ? false : hasValue; + this.kind = kind; + } + + var NotificationPrototype = Notification.prototype; + + /** + * Invokes the delegate corresponding to the notification or the observer's method corresponding to the notification and returns the produced result. + * + * @memberOf Notification + * @param {Any} observerOrOnNext Delegate to invoke for an OnNext notification or Observer to invoke the notification on.. + * @param {Function} onError Delegate to invoke for an OnError notification. + * @param {Function} onCompleted Delegate to invoke for an OnCompleted notification. + * @returns {Any} Result produced by the observation. + */ + NotificationPrototype.accept = function (observerOrOnNext, onError, onCompleted) { + if (arguments.length === 1 && typeof observerOrOnNext === 'object') { + return this._acceptObservable(observerOrOnNext); + } + return this._accept(observerOrOnNext, onError, onCompleted); + }; + + /** + * Returns an observable sequence with a single notification. + * + * @memberOf Notification + * @param {Scheduler} [scheduler] Scheduler to send out the notification calls on. + * @returns {Observable} The observable sequence that surfaces the behavior of the notification upon subscription. + */ + NotificationPrototype.toObservable = function (scheduler) { + var notification = this; + scheduler || (scheduler = immediateScheduler); + return new AnonymousObservable(function (observer) { + return scheduler.schedule(function () { + notification._acceptObservable(observer); + if (notification.kind === 'N') { + observer.onCompleted(); + } + }); + }); + }; + + return Notification; + })(); + + /** + * Creates an object that represents an OnNext notification to an observer. + * @param {Any} value The value contained in the notification. + * @returns {Notification} The OnNext notification containing the value. + */ + var notificationCreateOnNext = Notification.createOnNext = (function () { + + function _accept (onNext) { + return onNext(this.value); + } + + function _acceptObservable(observer) { + return observer.onNext(this.value); + } + + function toString () { + return 'OnNext(' + this.value + ')'; + } + + return function (value) { + var notification = new Notification('N', true); + notification.value = value; + notification._accept = _accept; + notification._acceptObservable = _acceptObservable; + notification.toString = toString; + return notification; + }; + }()); + + /** + * Creates an object that represents an OnError notification to an observer. + * @param {Any} error The exception contained in the notification. + * @returns {Notification} The OnError notification containing the exception. + */ + var notificationCreateOnError = Notification.createOnError = (function () { + + function _accept (onNext, onError) { + return onError(this.exception); + } + + function _acceptObservable(observer) { + return observer.onError(this.exception); + } + + function toString () { + return 'OnError(' + this.exception + ')'; + } + + return function (exception) { + var notification = new Notification('E'); + notification.exception = exception; + notification._accept = _accept; + notification._acceptObservable = _acceptObservable; + notification.toString = toString; + return notification; + }; + }()); + + /** + * Creates an object that represents an OnCompleted notification to an observer. + * @returns {Notification} The OnCompleted notification. + */ + var notificationCreateOnCompleted = Notification.createOnCompleted = (function () { + + function _accept (onNext, onError, onCompleted) { + return onCompleted(); + } + + function _acceptObservable(observer) { + return observer.onCompleted(); + } + + function toString () { + return 'OnCompleted()'; + } + + return function () { + var notification = new Notification('C'); + notification._accept = _accept; + notification._acceptObservable = _acceptObservable; + notification.toString = toString; + return notification; + }; + }()); + + var Enumerator = Rx.internals.Enumerator = function (next) { + this._next = next; + }; + + Enumerator.prototype.next = function () { + return this._next(); + }; + + Enumerator.prototype[$iterator$] = function () { return this; } + + var Enumerable = Rx.internals.Enumerable = function (iterator) { + this._iterator = iterator; + }; + + Enumerable.prototype[$iterator$] = function () { + return this._iterator(); + }; + + Enumerable.prototype.concat = function () { + var sources = this; + return new AnonymousObservable(function (observer) { + var e; + try { + e = sources[$iterator$](); + } catch(err) { + observer.onError(); + return; + } + + var isDisposed, + subscription = new SerialDisposable(); + var cancelable = immediateScheduler.scheduleRecursive(function (self) { + var currentItem; + if (isDisposed) { return; } + + try { + currentItem = e.next(); + } catch (ex) { + observer.onError(ex); + return; + } + + if (currentItem.done) { + observer.onCompleted(); + return; + } + + // Check if promise + var currentValue = currentItem.value; + isPromise(currentValue) && (currentValue = observableFromPromise(currentValue)); + + var d = new SingleAssignmentDisposable(); + subscription.setDisposable(d); + d.setDisposable(currentValue.subscribe( + observer.onNext.bind(observer), + observer.onError.bind(observer), + function () { self(); }) + ); + }); + + return new CompositeDisposable(subscription, cancelable, disposableCreate(function () { + isDisposed = true; + })); + }); + }; + + Enumerable.prototype.catchException = function () { + var sources = this; + return new AnonymousObservable(function (observer) { + var e; + try { + e = sources[$iterator$](); + } catch(err) { + observer.onError(); + return; + } + + var isDisposed, + lastException, + subscription = new SerialDisposable(); + var cancelable = immediateScheduler.scheduleRecursive(function (self) { + if (isDisposed) { return; } + + var currentItem; + try { + currentItem = e.next(); + } catch (ex) { + observer.onError(ex); + return; + } + + if (currentItem.done) { + if (lastException) { + observer.onError(lastException); + } else { + observer.onCompleted(); + } + return; + } + + // Check if promise + var currentValue = currentItem.value; + isPromise(currentValue) && (currentValue = observableFromPromise(currentValue)); + + var d = new SingleAssignmentDisposable(); + subscription.setDisposable(d); + d.setDisposable(currentValue.subscribe( + observer.onNext.bind(observer), + function (exn) { + lastException = exn; + self(); + }, + observer.onCompleted.bind(observer))); + }); + return new CompositeDisposable(subscription, cancelable, disposableCreate(function () { + isDisposed = true; + })); + }); + }; + + var enumerableRepeat = Enumerable.repeat = function (value, repeatCount) { + if (repeatCount == null) { repeatCount = -1; } + return new Enumerable(function () { + var left = repeatCount; + return new Enumerator(function () { + if (left === 0) { return doneEnumerator; } + if (left > 0) { left--; } + return { done: false, value: value }; + }); + }); + }; + + var enumerableFor = Enumerable.forEach = function (source, selector, thisArg) { + selector || (selector = identity); + return new Enumerable(function () { + var index = -1; + return new Enumerator( + function () { + return ++index < source.length ? + { done: false, value: selector.call(thisArg, source[index], index, source) } : + doneEnumerator; + }); + }); + }; + + /** + * Supports push-style iteration over an observable sequence. + */ + var Observer = Rx.Observer = function () { }; + + /** + * Creates a notification callback from an observer. + * + * @param observer Observer object. + * @returns The action that forwards its input notification to the underlying observer. + */ + Observer.prototype.toNotifier = function () { + var observer = this; + return function (n) { + return n.accept(observer); + }; + }; + + /** + * Hides the identity of an observer. + + * @returns An observer that hides the identity of the specified observer. + */ + Observer.prototype.asObserver = function () { + return new AnonymousObserver(this.onNext.bind(this), this.onError.bind(this), this.onCompleted.bind(this)); + }; + + /** + * Checks access to the observer for grammar violations. This includes checking for multiple OnError or OnCompleted calls, as well as reentrancy in any of the observer methods. + * If a violation is detected, an Error is thrown from the offending observer method call. + * + * @returns An observer that checks callbacks invocations against the observer grammar and, if the checks pass, forwards those to the specified observer. + */ + Observer.prototype.checked = function () { return new CheckedObserver(this); }; + + /** + * Creates an observer from the specified OnNext, along with optional OnError, and OnCompleted actions. + * + * @static + * @memberOf Observer + * @param {Function} [onNext] Observer's OnNext action implementation. + * @param {Function} [onError] Observer's OnError action implementation. + * @param {Function} [onCompleted] Observer's OnCompleted action implementation. + * @returns {Observer} The observer object implemented using the given actions. + */ + var observerCreate = Observer.create = function (onNext, onError, onCompleted) { + onNext || (onNext = noop); + onError || (onError = defaultError); + onCompleted || (onCompleted = noop); + return new AnonymousObserver(onNext, onError, onCompleted); + }; + + /** + * Creates an observer from a notification callback. + * + * @static + * @memberOf Observer + * @param {Function} handler Action that handles a notification. + * @returns The observer object that invokes the specified handler using a notification corresponding to each message it receives. + */ + Observer.fromNotifier = function (handler) { + return new AnonymousObserver(function (x) { + return handler(notificationCreateOnNext(x)); + }, function (exception) { + return handler(notificationCreateOnError(exception)); + }, function () { + return handler(notificationCreateOnCompleted()); + }); + }; + + /** + * Schedules the invocation of observer methods on the given scheduler. + * @param {Scheduler} scheduler Scheduler to schedule observer messages on. + * @returns {Observer} Observer whose messages are scheduled on the given scheduler. + */ + Observer.notifyOn = function (scheduler) { + return new ObserveOnObserver(scheduler, this); + }; + + /** + * Abstract base class for implementations of the Observer class. + * This base class enforces the grammar of observers where OnError and OnCompleted are terminal messages. + */ + var AbstractObserver = Rx.internals.AbstractObserver = (function (_super) { + inherits(AbstractObserver, _super); + + /** + * Creates a new observer in a non-stopped state. + * + * @constructor + */ + function AbstractObserver() { + this.isStopped = false; + _super.call(this); + } + + /** + * Notifies the observer of a new element in the sequence. + * + * @memberOf AbstractObserver + * @param {Any} value Next element in the sequence. + */ + AbstractObserver.prototype.onNext = function (value) { + if (!this.isStopped) { + this.next(value); + } + }; + + /** + * Notifies the observer that an exception has occurred. + * + * @memberOf AbstractObserver + * @param {Any} error The error that has occurred. + */ + AbstractObserver.prototype.onError = function (error) { + if (!this.isStopped) { + this.isStopped = true; + this.error(error); + } + }; + + /** + * Notifies the observer of the end of the sequence. + */ + AbstractObserver.prototype.onCompleted = function () { + if (!this.isStopped) { + this.isStopped = true; + this.completed(); + } + }; + + /** + * Disposes the observer, causing it to transition to the stopped state. + */ + AbstractObserver.prototype.dispose = function () { + this.isStopped = true; + }; + + AbstractObserver.prototype.fail = function (e) { + if (!this.isStopped) { + this.isStopped = true; + this.error(e); + return true; + } + + return false; + }; + + return AbstractObserver; + }(Observer)); + + /** + * Class to create an Observer instance from delegate-based implementations of the on* methods. + */ + var AnonymousObserver = Rx.AnonymousObserver = (function (_super) { + inherits(AnonymousObserver, _super); + + /** + * Creates an observer from the specified OnNext, OnError, and OnCompleted actions. + * @param {Any} onNext Observer's OnNext action implementation. + * @param {Any} onError Observer's OnError action implementation. + * @param {Any} onCompleted Observer's OnCompleted action implementation. + */ + function AnonymousObserver(onNext, onError, onCompleted) { + _super.call(this); + this._onNext = onNext; + this._onError = onError; + this._onCompleted = onCompleted; + } + + /** + * Calls the onNext action. + * @param {Any} value Next element in the sequence. + */ + AnonymousObserver.prototype.next = function (value) { + this._onNext(value); + }; + + /** + * Calls the onError action. + * @param {Any} error The error that has occurred. + */ + AnonymousObserver.prototype.error = function (exception) { + this._onError(exception); + }; + + /** + * Calls the onCompleted action. + */ + AnonymousObserver.prototype.completed = function () { + this._onCompleted(); + }; + + return AnonymousObserver; + }(AbstractObserver)); + + var CheckedObserver = (function (_super) { + inherits(CheckedObserver, _super); + + function CheckedObserver(observer) { + _super.call(this); + this._observer = observer; + this._state = 0; // 0 - idle, 1 - busy, 2 - done + } + + var CheckedObserverPrototype = CheckedObserver.prototype; + + CheckedObserverPrototype.onNext = function (value) { + this.checkAccess(); + try { + this._observer.onNext(value); + } catch (e) { + throw e; + } finally { + this._state = 0; + } + }; + + CheckedObserverPrototype.onError = function (err) { + this.checkAccess(); + try { + this._observer.onError(err); + } catch (e) { + throw e; + } finally { + this._state = 2; + } + }; + + CheckedObserverPrototype.onCompleted = function () { + this.checkAccess(); + try { + this._observer.onCompleted(); + } catch (e) { + throw e; + } finally { + this._state = 2; + } + }; + + CheckedObserverPrototype.checkAccess = function () { + if (this._state === 1) { throw new Error('Re-entrancy detected'); } + if (this._state === 2) { throw new Error('Observer completed'); } + if (this._state === 0) { this._state = 1; } + }; + + return CheckedObserver; + }(Observer)); + + var ScheduledObserver = Rx.internals.ScheduledObserver = (function (_super) { + inherits(ScheduledObserver, _super); + + function ScheduledObserver(scheduler, observer) { + _super.call(this); + this.scheduler = scheduler; + this.observer = observer; + this.isAcquired = false; + this.hasFaulted = false; + this.queue = []; + this.disposable = new SerialDisposable(); + } + + ScheduledObserver.prototype.next = function (value) { + var self = this; + this.queue.push(function () { + self.observer.onNext(value); + }); + }; + + ScheduledObserver.prototype.error = function (exception) { + var self = this; + this.queue.push(function () { + self.observer.onError(exception); + }); + }; + + ScheduledObserver.prototype.completed = function () { + var self = this; + this.queue.push(function () { + self.observer.onCompleted(); + }); + }; + + ScheduledObserver.prototype.ensureActive = function () { + var isOwner = false, parent = this; + if (!this.hasFaulted && this.queue.length > 0) { + isOwner = !this.isAcquired; + this.isAcquired = true; + } + if (isOwner) { + this.disposable.setDisposable(this.scheduler.scheduleRecursive(function (self) { + var work; + if (parent.queue.length > 0) { + work = parent.queue.shift(); + } else { + parent.isAcquired = false; + return; + } + try { + work(); + } catch (ex) { + parent.queue = []; + parent.hasFaulted = true; + throw ex; + } + self(); + })); + } + }; + + ScheduledObserver.prototype.dispose = function () { + _super.prototype.dispose.call(this); + this.disposable.dispose(); + }; + + return ScheduledObserver; + }(AbstractObserver)); + + /** @private */ + var ObserveOnObserver = (function (_super) { + inherits(ObserveOnObserver, _super); + + /** @private */ + function ObserveOnObserver() { + _super.apply(this, arguments); + } + + /** @private */ + ObserveOnObserver.prototype.next = function (value) { + _super.prototype.next.call(this, value); + this.ensureActive(); + }; + + /** @private */ + ObserveOnObserver.prototype.error = function (e) { + _super.prototype.error.call(this, e); + this.ensureActive(); + }; + + /** @private */ + ObserveOnObserver.prototype.completed = function () { + _super.prototype.completed.call(this); + this.ensureActive(); + }; + + return ObserveOnObserver; + })(ScheduledObserver); + + var observableProto; + + /** + * Represents a push-style collection. + */ + var Observable = Rx.Observable = (function () { + + function Observable(subscribe) { + this._subscribe = subscribe; + } + + observableProto = Observable.prototype; + + /** + * Subscribes an observer to the observable sequence. + * + * @example + * 1 - source.subscribe(); + * 2 - source.subscribe(observer); + * 3 - source.subscribe(function (x) { console.log(x); }); + * 4 - source.subscribe(function (x) { console.log(x); }, function (err) { console.log(err); }); + * 5 - source.subscribe(function (x) { console.log(x); }, function (err) { console.log(err); }, function () { console.log('done'); }); + * @param {Mixed} [observerOrOnNext] The object that is to receive notifications or an action to invoke for each element in the observable sequence. + * @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence. + * @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence. + * @returns {Diposable} The source sequence whose subscriptions and unsubscriptions happen on the specified scheduler. + */ + observableProto.subscribe = observableProto.forEach = function (observerOrOnNext, onError, onCompleted) { + var subscriber = typeof observerOrOnNext === 'object' ? + observerOrOnNext : + observerCreate(observerOrOnNext, onError, onCompleted); + + return this._subscribe(subscriber); + }; + + return Observable; + })(); + + var AnonymousObservable = Rx.AnonymousObservable = (function (__super__) { + inherits(AnonymousObservable, __super__); + + // Fix subscriber to check for undefined or function returned to decorate as Disposable + function fixSubscriber(subscriber) { + if (typeof subscriber === 'undefined') { + subscriber = disposableEmpty; + } else if (typeof subscriber === 'function') { + subscriber = disposableCreate(subscriber); + } + + return subscriber; + } + + function AnonymousObservable(subscribe) { + if (!(this instanceof AnonymousObservable)) { + return new AnonymousObservable(subscribe); + } + + function s(observer) { + var setDisposable = function () { + try { + autoDetachObserver.setDisposable(fixSubscriber(subscribe(autoDetachObserver))); + } catch (e) { + if (!autoDetachObserver.fail(e)) { + throw e; + } + } + }; + + var autoDetachObserver = new AutoDetachObserver(observer); + if (currentThreadScheduler.scheduleRequired()) { + currentThreadScheduler.schedule(setDisposable); + } else { + setDisposable(); + } + + return autoDetachObserver; + } + + __super__.call(this, s); + } + + return AnonymousObservable; + + }(Observable)); + + /** @private */ + var AutoDetachObserver = (function (_super) { + inherits(AutoDetachObserver, _super); + + function AutoDetachObserver(observer) { + _super.call(this); + this.observer = observer; + this.m = new SingleAssignmentDisposable(); + } + + var AutoDetachObserverPrototype = AutoDetachObserver.prototype; + + AutoDetachObserverPrototype.next = function (value) { + var noError = false; + try { + this.observer.onNext(value); + noError = true; + } catch (e) { + throw e; + } finally { + if (!noError) { + this.dispose(); + } + } + }; + + AutoDetachObserverPrototype.error = function (exn) { + try { + this.observer.onError(exn); + } catch (e) { + throw e; + } finally { + this.dispose(); + } + }; + + AutoDetachObserverPrototype.completed = function () { + try { + this.observer.onCompleted(); + } catch (e) { + throw e; + } finally { + this.dispose(); + } + }; + + AutoDetachObserverPrototype.setDisposable = function (value) { this.m.setDisposable(value); }; + AutoDetachObserverPrototype.getDisposable = function (value) { return this.m.getDisposable(); }; + /* @private */ + AutoDetachObserverPrototype.disposable = function (value) { + return arguments.length ? this.getDisposable() : setDisposable(value); + }; + + AutoDetachObserverPrototype.dispose = function () { + _super.prototype.dispose.call(this); + this.m.dispose(); + }; + + return AutoDetachObserver; + }(AbstractObserver)); + + /** @private */ + var GroupedObservable = (function (_super) { + inherits(GroupedObservable, _super); + + function subscribe(observer) { + return this.underlyingObservable.subscribe(observer); + } + + /** + * @constructor + * @private + */ + function GroupedObservable(key, underlyingObservable, mergedDisposable) { + _super.call(this, subscribe); + this.key = key; + this.underlyingObservable = !mergedDisposable ? + underlyingObservable : + new AnonymousObservable(function (observer) { + return new CompositeDisposable(mergedDisposable.getDisposable(), underlyingObservable.subscribe(observer)); + }); + } + + return GroupedObservable; + }(Observable)); + + /** @private */ + var InnerSubscription = function (subject, observer) { + this.subject = subject; + this.observer = observer; + }; + + /** + * @private + * @memberOf InnerSubscription + */ + InnerSubscription.prototype.dispose = function () { + if (!this.subject.isDisposed && this.observer !== null) { + var idx = this.subject.observers.indexOf(this.observer); + this.subject.observers.splice(idx, 1); + this.observer = null; + } + }; + + /** + * Represents an object that is both an observable sequence as well as an observer. + * Each notification is broadcasted to all subscribed observers. + */ + var Subject = Rx.Subject = (function (_super) { + function subscribe(observer) { + checkDisposed.call(this); + if (!this.isStopped) { + this.observers.push(observer); + return new InnerSubscription(this, observer); + } + if (this.exception) { + observer.onError(this.exception); + return disposableEmpty; + } + observer.onCompleted(); + return disposableEmpty; + } + + inherits(Subject, _super); + + /** + * Creates a subject. + * @constructor + */ + function Subject() { + _super.call(this, subscribe); + this.isDisposed = false, + this.isStopped = false, + this.observers = []; + } + + addProperties(Subject.prototype, Observer, { + /** + * Indicates whether the subject has observers subscribed to it. + * @returns {Boolean} Indicates whether the subject has observers subscribed to it. + */ + hasObservers: function () { + return this.observers.length > 0; + }, + /** + * Notifies all subscribed observers about the end of the sequence. + */ + onCompleted: function () { + checkDisposed.call(this); + if (!this.isStopped) { + var os = this.observers.slice(0); + this.isStopped = true; + for (var i = 0, len = os.length; i < len; i++) { + os[i].onCompleted(); + } + + this.observers = []; + } + }, + /** + * Notifies all subscribed observers about the exception. + * @param {Mixed} error The exception to send to all observers. + */ + onError: function (exception) { + checkDisposed.call(this); + if (!this.isStopped) { + var os = this.observers.slice(0); + this.isStopped = true; + this.exception = exception; + for (var i = 0, len = os.length; i < len; i++) { + os[i].onError(exception); + } + + this.observers = []; + } + }, + /** + * Notifies all subscribed observers about the arrival of the specified element in the sequence. + * @param {Mixed} value The value to send to all observers. + */ + onNext: function (value) { + checkDisposed.call(this); + if (!this.isStopped) { + var os = this.observers.slice(0); + for (var i = 0, len = os.length; i < len; i++) { + os[i].onNext(value); + } + } + }, + /** + * Unsubscribe all observers and release resources. + */ + dispose: function () { + this.isDisposed = true; + this.observers = null; + } + }); + + /** + * Creates a subject from the specified observer and observable. + * @param {Observer} observer The observer used to send messages to the subject. + * @param {Observable} observable The observable used to subscribe to messages sent from the subject. + * @returns {Subject} Subject implemented using the given observer and observable. + */ + Subject.create = function (observer, observable) { + return new AnonymousSubject(observer, observable); + }; + + return Subject; + }(Observable)); + + /** + * Represents the result of an asynchronous operation. + * The last value before the OnCompleted notification, or the error received through OnError, is sent to all subscribed observers. + */ + var AsyncSubject = Rx.AsyncSubject = (function (_super) { + + function subscribe(observer) { + checkDisposed.call(this); + + if (!this.isStopped) { + this.observers.push(observer); + return new InnerSubscription(this, observer); + } + + var ex = this.exception, + hv = this.hasValue, + v = this.value; + + if (ex) { + observer.onError(ex); + } else if (hv) { + observer.onNext(v); + observer.onCompleted(); + } else { + observer.onCompleted(); + } + + return disposableEmpty; + } + + inherits(AsyncSubject, _super); + + /** + * Creates a subject that can only receive one value and that value is cached for all future observations. + * @constructor + */ + function AsyncSubject() { + _super.call(this, subscribe); + + this.isDisposed = false; + this.isStopped = false; + this.value = null; + this.hasValue = false; + this.observers = []; + this.exception = null; + } + + addProperties(AsyncSubject.prototype, Observer, { + /** + * Indicates whether the subject has observers subscribed to it. + * @returns {Boolean} Indicates whether the subject has observers subscribed to it. + */ + hasObservers: function () { + checkDisposed.call(this); + return this.observers.length > 0; + }, + /** + * Notifies all subscribed observers about the end of the sequence, also causing the last received value to be sent out (if any). + */ + onCompleted: function () { + var o, i, len; + checkDisposed.call(this); + if (!this.isStopped) { + this.isStopped = true; + var os = this.observers.slice(0), + v = this.value, + hv = this.hasValue; + + if (hv) { + for (i = 0, len = os.length; i < len; i++) { + o = os[i]; + o.onNext(v); + o.onCompleted(); + } + } else { + for (i = 0, len = os.length; i < len; i++) { + os[i].onCompleted(); + } + } + + this.observers = []; + } + }, + /** + * Notifies all subscribed observers about the exception. + * @param {Mixed} error The exception to send to all observers. + */ + onError: function (exception) { + checkDisposed.call(this); + if (!this.isStopped) { + var os = this.observers.slice(0); + this.isStopped = true; + this.exception = exception; + + for (var i = 0, len = os.length; i < len; i++) { + os[i].onError(exception); + } + + this.observers = []; + } + }, + /** + * Sends a value to the subject. The last value received before successful termination will be sent to all subscribed and future observers. + * @param {Mixed} value The value to store in the subject. + */ + onNext: function (value) { + checkDisposed.call(this); + if (!this.isStopped) { + this.value = value; + this.hasValue = true; + } + }, + /** + * Unsubscribe all observers and release resources. + */ + dispose: function () { + this.isDisposed = true; + this.observers = null; + this.exception = null; + this.value = null; + } + }); + + return AsyncSubject; + }(Observable)); + + /** @private */ + var AnonymousSubject = (function (_super) { + inherits(AnonymousSubject, _super); + + function subscribe(observer) { + return this.observable.subscribe(observer); + } + + /** + * @private + * @constructor + */ + function AnonymousSubject(observer, observable) { + _super.call(this, subscribe); + this.observer = observer; + this.observable = observable; + } + + addProperties(AnonymousSubject.prototype, Observer, { + /** + * @private + * @memberOf AnonymousSubject# + */ + onCompleted: function () { + this.observer.onCompleted(); + }, + /** + * @private + * @memberOf AnonymousSubject# + */ + onError: function (exception) { + this.observer.onError(exception); + }, + /** + * @private + * @memberOf AnonymousSubject# + */ + onNext: function (value) { + this.observer.onNext(value); + } + }); + + return AnonymousSubject; + }(Observable)); + + if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) { + root.Rx = Rx; + + define(function() { + return Rx; + }); + } else if (freeExports && freeModule) { + // in Node.js or RingoJS + if (moduleExports) { + (freeModule.exports = Rx).Rx = Rx; + } else { + freeExports.Rx = Rx; + } + } else { + // in a browser or Rhino + root.Rx = Rx; + } +}.call(this)); \ No newline at end of file diff --git a/ajax/libs/rxjs/2.2.28/rx.core.min.js b/ajax/libs/rxjs/2.2.28/rx.core.min.js new file mode 100644 index 000000000..114f0b28f --- /dev/null +++ b/ajax/libs/rxjs/2.2.28/rx.core.min.js @@ -0,0 +1 @@ +(function(t){function e(){if(this.isDisposed)throw Error(A)}function n(t){var e=typeof t;return t&&("function"==e||"object"==e)||!1}function i(t){var e=[];if(!n(t))return e;G.nonEnumArgs&&t.length&&u(t)&&(t=U.call(t));var i=G.enumPrototypes&&"function"==typeof t,r=G.enumErrorProps&&(t===H||t instanceof Error);for(var s in t)i&&"prototype"==s||r&&("message"==s||"name"==s)||e.push(s);if(G.nonEnumShadows&&t!==L){var o=t.constructor,c=-1,h=K.length;if(t===(o&&o.prototype))var a=t===stringProto?M:t===H?N:F.call(t),l=Q[a];for(;h>++c;)s=K[c],l&&l[s]||!z.call(t,s)||e.push(s)}return e}function r(t,e,n){for(var i=-1,r=n(t),s=r.length;s>++i;){var o=r[i];if(e(t[o],o,t)===!1)break}return t}function s(t,e){return r(t,e,i)}function o(t){return"function"!=typeof t.toString&&"string"==typeof(t+"")}function u(t){return t&&"object"==typeof t?F.call(t)==C:!1}function c(t){return"function"==typeof t||!1}function h(e,n,i,r){if(e===n)return 0!==e||1/e==1/n;var a=typeof e,l=typeof n;if(e===e&&(null==e||null==n||"function"!=a&&"object"!=a&&"function"!=l&&"object"!=l))return!1;var p=F.call(e),f=F.call(n);if(p==C&&(p=T),f==C&&(f=T),p!=f)return!1;switch(p){case W:case P:return+e==+n;case k:return e!=+e?n!=+n:0==e?1/e==1/n:e==+n;case I:case M:return e==n+""}var d=p==j;if(!d){if(p!=T||!G.nodeClass&&(o(e)||o(n)))return!1;var v=!G.argsObject&&u(e)?Object:e.constructor,b=!G.argsObject&&u(n)?Object:n.constructor;if(!(v==b||z.call(e,"constructor")&&z.call(n,"constructor")||c(v)&&v instanceof v&&c(b)&&b instanceof b||!("constructor"in e&&"constructor"in n)))return!1}i||(i=[]),r||(r=[]);for(var y=i.length;y--;)if(i[y]==e)return r[y]==n;var m=0;if(result=!0,i.push(e),r.push(n),d){if(y=e.length,m=n.length,result=m==y)for(;m--;){var g=n[m];if(!(result=h(e[m],g,i,r)))break}}else s(n,function(n,s,o){return z.call(o,s)?(m++,result=z.call(e,s)&&h(e[s],n,i,r)):t}),result&&s(e,function(e,n,i){return z.call(i,n)?result=--m>-1:t});return i.pop(),r.pop(),result}function a(t,e){return 1===t.length&&Array.isArray(t[e])?t[e]:U.call(t)}function l(t,e){this.scheduler=t,this.disposable=e,this.isDisposed=!1}var p={"boolean":!1,"function":!0,object:!0,number:!1,string:!1,undefined:!1},f=p[typeof window]&&window||this,d=p[typeof exports]&&exports&&!exports.nodeType&&exports,v=p[typeof module]&&module&&!module.nodeType&&module,b=v&&v.exports===d&&d,y=p[typeof global]&&global;!y||y.global!==y&&y.window!==y||(f=y);var m={internals:{},config:{Promise:f.Promise},helpers:{}},g=m.helpers.noop=function(){},w=m.helpers.identity=function(t){return t},_=(m.helpers.pluck=function(t){return function(e){return e[t]}},m.helpers.just=function(t){return function(){return t}},m.helpers.defaultNow=Date.now),S=(m.helpers.defaultComparer=function(t,e){return J(t,e)},m.helpers.defaultSubComparer=function(t,e){return t>e?1:e>t?-1:0}),D=(m.helpers.defaultKeySerializer=function(t){return""+t},m.helpers.defaultError=function(t){throw t}),x=m.helpers.isPromise=function(t){return!!t&&"function"==typeof t.then&&t.then!==m.Observable.prototype.then};m.helpers.asArray=function(){return Array.prototype.slice.call(arguments)},m.helpers.not=function(t){return!t};var A="Object has been disposed",E="object"==typeof Symbol&&Symbol.iterator||"_es6shim_iterator_";f.Set&&"function"==typeof(new f.Set)["@@iterator"]&&(E="@@iterator");var O,R={done:!0,value:t},C="[object Arguments]",j="[object Array]",W="[object Boolean]",P="[object Date]",N="[object Error]",q="[object Function]",k="[object Number]",T="[object Object]",I="[object RegExp]",M="[object String]",F=Object.prototype.toString,z=Object.prototype.hasOwnProperty,V=F.call(arguments)==C,H=Error.prototype,L=Object.prototype,$=L.propertyIsEnumerable;try{O=!(F.call(document)==T&&!({toString:0}+""))}catch(B){O=!0}var K=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],Q={};Q[j]=Q[P]=Q[k]={constructor:!0,toLocaleString:!0,toString:!0,valueOf:!0},Q[W]=Q[M]={constructor:!0,toString:!0,valueOf:!0},Q[N]=Q[q]=Q[I]={constructor:!0,toString:!0},Q[T]={constructor:!0};var G={};(function(){var t=function(){this.x=1},e=[];t.prototype={valueOf:1,y:1};for(var n in new t)e.push(n);for(n in arguments);G.enumErrorProps=$.call(H,"message")||$.call(H,"name"),G.enumPrototypes=$.call(t,"prototype"),G.nonEnumArgs=0!=n,G.nonEnumShadows=!/valueOf/.test(e)})(1),V||(u=function(t){return t&&"object"==typeof t?z.call(t,"callee"):!1}),c(/x/)&&(c=function(t){return"function"==typeof t&&F.call(t)==q});var J=m.internals.isEqual=function(t,e){return h(t,e,[],[])},U=Array.prototype.slice;({}).hasOwnProperty;var X=this.inherits=m.internals.inherits=function(t,e){function n(){this.constructor=t}n.prototype=e.prototype,t.prototype=new n},Y=m.internals.addProperties=function(t){for(var e=U.call(arguments,1),n=0,i=e.length;i>n;n++){var r=e[n];for(var s in r)t[s]=r[s]}};m.internals.addRef=function(t,e){return new Ne(function(n){return new ne(e.getDisposable(),t.subscribe(n))})};var Z=function(t,e){this.id=t,this.value=e};Z.prototype.compareTo=function(t){var e=this.value.compareTo(t.value);return 0===e&&(e=this.id-t.id),e};var te=m.internals.PriorityQueue=function(t){this.items=Array(t),this.length=0},ee=te.prototype;ee.isHigherPriority=function(t,e){return 0>this.items[t].compareTo(this.items[e])},ee.percolate=function(t){if(!(t>=this.length||0>t)){var e=t-1>>1;if(!(0>e||e===t)&&this.isHigherPriority(t,e)){var n=this.items[t];this.items[t]=this.items[e],this.items[e]=n,this.percolate(e)}}},ee.heapify=function(e){if(e===t&&(e=0),!(e>=this.length||0>e)){var n=2*e+1,i=2*e+2,r=e;if(this.length>n&&this.isHigherPriority(n,r)&&(r=n),this.length>i&&this.isHigherPriority(i,r)&&(r=i),r!==e){var s=this.items[e];this.items[e]=this.items[r],this.items[r]=s,this.heapify(r)}}},ee.peek=function(){return this.items[0].value},ee.removeAt=function(t){this.items[t]=this.items[--this.length],delete this.items[this.length],this.heapify()},ee.dequeue=function(){var t=this.peek();return this.removeAt(0),t},ee.enqueue=function(t){var e=this.length++;this.items[e]=new Z(te.count++,t),this.percolate(e)},ee.remove=function(t){for(var e=0;this.length>e;e++)if(this.items[e].value===t)return this.removeAt(e),!0;return!1},te.count=0;var ne=m.CompositeDisposable=function(){this.disposables=a(arguments,0),this.isDisposed=!1,this.length=this.disposables.length},ie=ne.prototype;ie.add=function(t){this.isDisposed?t.dispose():(this.disposables.push(t),this.length++)},ie.remove=function(t){var e=!1;if(!this.isDisposed){var n=this.disposables.indexOf(t);-1!==n&&(e=!0,this.disposables.splice(n,1),this.length--,t.dispose())}return e},ie.dispose=function(){if(!this.isDisposed){this.isDisposed=!0;var t=this.disposables.slice(0);this.disposables=[],this.length=0;for(var e=0,n=t.length;n>e;e++)t[e].dispose()}},ie.clear=function(){var t=this.disposables.slice(0);this.disposables=[],this.length=0;for(var e=0,n=t.length;n>e;e++)t[e].dispose()},ie.contains=function(t){return-1!==this.disposables.indexOf(t)},ie.toArray=function(){return this.disposables.slice(0)};var re=m.Disposable=function(t){this.isDisposed=!1,this.action=t||g};re.prototype.dispose=function(){this.isDisposed||(this.action(),this.isDisposed=!0)};var se=re.create=function(t){return new re(t)},oe=re.empty={dispose:g},ue=function(){function t(t){this.isSingle=t,this.isDisposed=!1,this.current=null}var e=t.prototype;return e.getDisposable=function(){return this.current},e.setDisposable=function(t){if(this.current&&this.isSingle)throw Error("Disposable has already been assigned");var e,n=this.isDisposed;n||(e=this.current,this.current=t),e&&e.dispose(),n&&t&&t.dispose()},e.dispose=function(){var t;this.isDisposed||(this.isDisposed=!0,t=this.current,this.current=null),t&&t.dispose()},t}(),ce=m.SingleAssignmentDisposable=function(t){function e(){t.call(this,!0)}return X(e,t),e}(ue),he=m.SerialDisposable=function(t){function e(){t.call(this,!1)}return X(e,t),e}(ue);m.RefCountDisposable=function(){function t(t){this.disposable=t,this.disposable.count++,this.isInnerDisposed=!1}function e(t){this.underlyingDisposable=t,this.isDisposed=!1,this.isPrimaryDisposed=!1,this.count=0}return t.prototype.dispose=function(){this.disposable.isDisposed||this.isInnerDisposed||(this.isInnerDisposed=!0,this.disposable.count--,0===this.disposable.count&&this.disposable.isPrimaryDisposed&&(this.disposable.isDisposed=!0,this.disposable.underlyingDisposable.dispose()))},e.prototype.dispose=function(){this.isDisposed||this.isPrimaryDisposed||(this.isPrimaryDisposed=!0,0===this.count&&(this.isDisposed=!0,this.underlyingDisposable.dispose()))},e.prototype.getDisposable=function(){return this.isDisposed?oe:new t(this)},e}(),l.prototype.dispose=function(){var t=this;this.scheduler.schedule(function(){t.isDisposed||(t.isDisposed=!0,t.disposable.dispose())})};var ae=m.internals.ScheduledItem=function(t,e,n,i,r){this.scheduler=t,this.state=e,this.action=n,this.dueTime=i,this.comparer=r||S,this.disposable=new ce};ae.prototype.invoke=function(){this.disposable.setDisposable(this.invokeCore())},ae.prototype.compareTo=function(t){return this.comparer(this.dueTime,t.dueTime)},ae.prototype.isCancelled=function(){return this.disposable.isDisposed},ae.prototype.invokeCore=function(){return this.action(this.scheduler,this.state)};var le=m.Scheduler=function(){function t(t,e,n,i){this.now=t,this._schedule=e,this._scheduleRelative=n,this._scheduleAbsolute=i}function e(t,e){var n=e.first,i=e.second,r=new ne,s=function(e){i(e,function(e){var n=!1,i=!1,o=t.scheduleWithState(e,function(t,e){return n?r.remove(o):i=!0,s(e),oe});i||(r.add(o),n=!0)})};return s(n),r}function n(t,e,n){var i=e.first,r=e.second,s=new ne,o=function(e){r(e,function(e,i){var r=!1,u=!1,c=t[n].call(t,e,i,function(t,e){return r?s.remove(c):u=!0,o(e),oe});u||(s.add(c),r=!0)})};return o(i),s}function i(t,e){return e(),oe}var r=t.prototype;return r.catchException=r["catch"]=function(t){return new ye(this,t)},r.schedulePeriodic=function(t,e){return this.schedulePeriodicWithState(null,t,function(){e()})},r.schedulePeriodicWithState=function(t,e,n){var i=t,r=setInterval(function(){i=n(i)},e);return se(function(){clearInterval(r)})},r.schedule=function(t){return this._schedule(t,i)},r.scheduleWithState=function(t,e){return this._schedule(t,e)},r.scheduleWithRelative=function(t,e){return this._scheduleRelative(e,t,i)},r.scheduleWithRelativeAndState=function(t,e,n){return this._scheduleRelative(t,e,n)},r.scheduleWithAbsolute=function(t,e){return this._scheduleAbsolute(e,t,i)},r.scheduleWithAbsoluteAndState=function(t,e,n){return this._scheduleAbsolute(t,e,n)},r.scheduleRecursive=function(t){return this.scheduleRecursiveWithState(t,function(t,e){t(function(){e(t)})})},r.scheduleRecursiveWithState=function(t,n){return this.scheduleWithState({first:t,second:n},function(t,n){return e(t,n)})},r.scheduleRecursiveWithRelative=function(t,e){return this.scheduleRecursiveWithRelativeAndState(e,t,function(t,e){t(function(n){e(t,n)})})},r.scheduleRecursiveWithRelativeAndState=function(t,e,i){return this._scheduleRelative({first:t,second:i},e,function(t,e){return n(t,e,"scheduleWithRelativeAndState")})},r.scheduleRecursiveWithAbsolute=function(t,e){return this.scheduleRecursiveWithAbsoluteAndState(e,t,function(t,e){t(function(n){e(t,n)})})},r.scheduleRecursiveWithAbsoluteAndState=function(t,e,i){return this._scheduleAbsolute({first:t,second:i},e,function(t,e){return n(t,e,"scheduleWithAbsoluteAndState")})},t.now=_,t.normalize=function(t){return 0>t&&(t=0),t},t}(),pe=le.normalize;m.internals.SchedulePeriodicRecursive=function(){function t(t,e){e(0,this._period);try{this._state=this._action(this._state)}catch(n){throw this._cancel.dispose(),n}}function e(t,e,n,i){this._scheduler=t,this._state=e,this._period=n,this._action=i}return e.prototype.start=function(){var e=new ce;return this._cancel=e,e.setDisposable(this._scheduler.scheduleRecursiveWithRelativeAndState(0,this._period,t.bind(this))),e},e}();var fe,de=le.immediate=function(){function t(t,e){return e(this,t)}function e(t,e,n){for(var i=pe(i);i-this.now()>0;);return n(this,t)}function n(t,e,n){return this.scheduleWithRelativeAndState(t,e-this.now(),n)}return new le(_,t,e,n)}(),ve=le.currentThread=function(){function t(t){for(var e;t.length>0;)if(e=t.dequeue(),!e.isCancelled()){for(;e.dueTime-le.now()>0;);e.isCancelled()||e.invoke()}}function e(t,e){return this.scheduleWithRelativeAndState(t,0,e)}function n(e,n,i){var s=this.now()+le.normalize(n),o=new ae(this,e,i,s);if(r)r.enqueue(o);else{r=new te(4),r.enqueue(o);try{t(r)}catch(u){throw u}finally{r=null}}return o.disposable}function i(t,e,n){return this.scheduleWithRelativeAndState(t,e-this.now(),n)}var r,s=new le(_,e,n,i);return s.scheduleRequired=function(){return null===r},s.ensureTrampoline=function(t){return null===r?this.schedule(t):t()},s}(),be=g;(function(){function t(){if(!f.postMessage||f.importScripts)return!1;var t=!1,e=f.onmessage;return f.onmessage=function(){t=!0},f.postMessage("","*"),f.onmessage=e,t}function e(t){if("string"==typeof t.data&&t.data.substring(0,s.length)===s){var e=t.data.substring(s.length),n=o[e];n(),delete o[e]}}var n=RegExp("^"+(F+"").replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/toString| for [^\]]+/g,".*?")+"$"),i="function"==typeof(i=y&&b&&y.setImmediate)&&!n.test(i)&&i,r="function"==typeof(r=y&&b&&y.clearImmediate)&&!n.test(r)&&r;if("undefined"!=typeof process&&"[object process]"==={}.toString.call(process))fe=process.nextTick;else if("function"==typeof i)fe=i,be=r;else if(t()){var s="ms.rx.schedule"+Math.random(),o={},u=0;f.addEventListener?f.addEventListener("message",e,!1):f.attachEvent("onmessage",e,!1),fe=function(t){var e=u++;o[e]=t,f.postMessage(s+e,"*")}}else if(f.MessageChannel){var c=new f.MessageChannel,h={},a=0;c.port1.onmessage=function(t){var e=t.data,n=h[e];n(),delete h[e]},fe=function(t){var e=a++;h[e]=t,c.port2.postMessage(e)}}else"document"in f&&"onreadystatechange"in f.document.createElement("script")?fe=function(t){var e=f.document.createElement("script");e.onreadystatechange=function(){t(),e.onreadystatechange=null,e.parentNode.removeChild(e),e=null},f.document.documentElement.appendChild(e)}:(fe=function(t){return setTimeout(t,0)},be=clearTimeout)})(),le.timeout=function(){function t(t,e){var n=this,i=new ce,r=fe(function(){i.isDisposed||i.setDisposable(e(n,t))});return new ne(i,se(function(){be(r)}))}function e(t,e,n){var i=this,r=le.normalize(e);if(0===r)return i.scheduleWithState(t,n);var s=new ce,o=setTimeout(function(){s.isDisposed||s.setDisposable(n(i,t))},r);return new ne(s,se(function(){clearTimeout(o)}))}function n(t,e,n){return this.scheduleWithRelativeAndState(t,e-this.now(),n)}return new le(_,t,e,n)}();var ye=function(t){function e(){return this._scheduler.now()}function n(t,e){return this._scheduler.scheduleWithState(t,this._wrap(e))}function i(t,e,n){return this._scheduler.scheduleWithRelativeAndState(t,e,this._wrap(n))}function r(t,e,n){return this._scheduler.scheduleWithAbsoluteAndState(t,e,this._wrap(n))}function s(s,o){this._scheduler=s,this._handler=o,this._recursiveOriginal=null,this._recursiveWrapper=null,t.call(this,e,n,i,r)}return X(s,t),s.prototype._clone=function(t){return new s(t,this._handler)},s.prototype._wrap=function(t){var e=this;return function(n,i){try{return t(e._getRecursiveWrapper(n),i)}catch(r){if(!e._handler(r))throw r;return oe}}},s.prototype._getRecursiveWrapper=function(t){if(this._recursiveOriginal!==t){this._recursiveOriginal=t;var e=this._clone(t);e._recursiveOriginal=t,e._recursiveWrapper=e,this._recursiveWrapper=e}return this._recursiveWrapper},s.prototype.schedulePeriodicWithState=function(t,e,n){var i=this,r=!1,s=new ce;return s.setDisposable(this._scheduler.schedulePeriodicWithState(t,e,function(t){if(r)return null;try{return n(t)}catch(e){if(r=!0,!i._handler(e))throw e;return s.dispose(),null}})),s},s}(le),me=m.Notification=function(){function t(t,e){this.hasValue=null==e?!1:e,this.kind=t}var e=t.prototype;return e.accept=function(t,e,n){return 1===arguments.length&&"object"==typeof t?this._acceptObservable(t):this._accept(t,e,n)},e.toObservable=function(t){var e=this;return t||(t=de),new Ne(function(n){return t.schedule(function(){e._acceptObservable(n),"N"===e.kind&&n.onCompleted()})})},t}(),ge=me.createOnNext=function(){function t(t){return t(this.value)}function e(t){return t.onNext(this.value)}function n(){return"OnNext("+this.value+")"}return function(i){var r=new me("N",!0);return r.value=i,r._accept=t,r._acceptObservable=e,r.toString=n,r}}(),we=me.createOnError=function(){function t(t,e){return e(this.exception)}function e(t){return t.onError(this.exception)}function n(){return"OnError("+this.exception+")"}return function(i){var r=new me("E");return r.exception=i,r._accept=t,r._acceptObservable=e,r.toString=n,r}}(),_e=me.createOnCompleted=function(){function t(t,e,n){return n()}function e(t){return t.onCompleted()}function n(){return"OnCompleted()"}return function(){var i=new me("C");return i._accept=t,i._acceptObservable=e,i.toString=n,i}}(),Se=m.internals.Enumerator=function(t){this._next=t};Se.prototype.next=function(){return this._next()},Se.prototype[E]=function(){return this};var De=m.internals.Enumerable=function(t){this._iterator=t};De.prototype[E]=function(){return this._iterator()},De.prototype.concat=function(){var e=this;return new Ne(function(n){var i;try{i=e[E]()}catch(r){return n.onError(),t}var s,o=new he,u=de.scheduleRecursive(function(e){var r;if(!s){try{r=i.next()}catch(u){return n.onError(u),t}if(r.done)return n.onCompleted(),t;var c=r.value;x(c)&&(c=observableFromPromise(c));var h=new ce;o.setDisposable(h),h.setDisposable(c.subscribe(n.onNext.bind(n),n.onError.bind(n),function(){e()}))}});return new ne(o,u,se(function(){s=!0}))})},De.prototype.catchException=function(){var e=this;return new Ne(function(n){var i;try{i=e[E]()}catch(r){return n.onError(),t}var s,o,u=new he,c=de.scheduleRecursive(function(e){if(!s){var r;try{r=i.next()}catch(c){return n.onError(c),t}if(r.done)return o?n.onError(o):n.onCompleted(),t;var h=r.value;x(h)&&(h=observableFromPromise(h));var a=new ce;u.setDisposable(a),a.setDisposable(h.subscribe(n.onNext.bind(n),function(t){o=t,e()},n.onCompleted.bind(n)))}});return new ne(u,c,se(function(){s=!0}))})},De.repeat=function(t,e){return null==e&&(e=-1),new De(function(){var n=e;return new Se(function(){return 0===n?R:(n>0&&n--,{done:!1,value:t})})})},De.forEach=function(t,e,n){return e||(e=w),new De(function(){var i=-1;return new Se(function(){return++i0&&(e=!this.isAcquired,this.isAcquired=!0),e&&this.disposable.setDisposable(this.scheduler.scheduleRecursive(function(e){var i;if(!(n.queue.length>0))return n.isAcquired=!1,t;i=n.queue.shift();try{i()}catch(r){throw n.queue=[],n.hasFaulted=!0,r}e()}))},n.prototype.dispose=function(){e.prototype.dispose.call(this),this.disposable.dispose()},n}(Oe),We=function(t){function e(){t.apply(this,arguments)}return X(e,t),e.prototype.next=function(e){t.prototype.next.call(this,e),this.ensureActive()},e.prototype.error=function(e){t.prototype.error.call(this,e),this.ensureActive()},e.prototype.completed=function(){t.prototype.completed.call(this),this.ensureActive()},e}(je),Pe=m.Observable=function(){function t(t){this._subscribe=t}return Ee=t.prototype,Ee.subscribe=Ee.forEach=function(t,e,n){var i="object"==typeof t?t:Ae(t,e,n);return this._subscribe(i)},t}(),Ne=m.AnonymousObservable=function(e){function n(e){return e===t?e=oe:"function"==typeof e&&(e=se(e)),e}function i(r){function s(t){var e=function(){try{i.setDisposable(n(r(i)))}catch(t){if(!i.fail(t))throw t}},i=new qe(t);return ve.scheduleRequired()?ve.schedule(e):e(),i}return this instanceof i?(e.call(this,s),t):new i(r)}return X(i,e),i}(Pe),qe=function(t){function e(e){t.call(this),this.observer=e,this.m=new ce}X(e,t);var n=e.prototype;return n.next=function(t){var e=!1;try{this.observer.onNext(t),e=!0}catch(n){throw n}finally{e||this.dispose()}},n.error=function(t){try{this.observer.onError(t)}catch(e){throw e}finally{this.dispose()}},n.completed=function(){try{this.observer.onCompleted()}catch(t){throw t}finally{this.dispose()}},n.setDisposable=function(t){this.m.setDisposable(t)},n.getDisposable=function(){return this.m.getDisposable()},n.disposable=function(t){return arguments.length?this.getDisposable():setDisposable(t)},n.dispose=function(){t.prototype.dispose.call(this),this.m.dispose()},e}(Oe);(function(t){function e(t){return this.underlyingObservable.subscribe(t)}function n(n,i,r){t.call(this,e),this.key=n,this.underlyingObservable=r?new Ne(function(t){return new ne(r.getDisposable(),i.subscribe(t))}):i}return X(n,t),n})(Pe);var ke=function(t,e){this.subject=t,this.observer=e};ke.prototype.dispose=function(){if(!this.subject.isDisposed&&null!==this.observer){var t=this.subject.observers.indexOf(this.observer);this.subject.observers.splice(t,1),this.observer=null}},m.Subject=function(t){function n(t){return e.call(this),this.isStopped?this.exception?(t.onError(this.exception),oe):(t.onCompleted(),oe):(this.observers.push(t),new ke(this,t))}function i(){t.call(this,n),this.isDisposed=!1,this.isStopped=!1,this.observers=[]}return X(i,t),Y(i.prototype,xe,{hasObservers:function(){return this.observers.length>0},onCompleted:function(){if(e.call(this),!this.isStopped){var t=this.observers.slice(0);this.isStopped=!0;for(var n=0,i=t.length;i>n;n++)t[n].onCompleted();this.observers=[]}},onError:function(t){if(e.call(this),!this.isStopped){var n=this.observers.slice(0);this.isStopped=!0,this.exception=t;for(var i=0,r=n.length;r>i;i++)n[i].onError(t);this.observers=[]}},onNext:function(t){if(e.call(this),!this.isStopped)for(var n=this.observers.slice(0),i=0,r=n.length;r>i;i++)n[i].onNext(t)},dispose:function(){this.isDisposed=!0,this.observers=null}}),i.create=function(t,e){return new Te(t,e)},i}(Pe),m.AsyncSubject=function(t){function n(t){if(e.call(this),!this.isStopped)return this.observers.push(t),new ke(this,t);var n=this.exception,i=this.hasValue,r=this.value;return n?t.onError(n):i?(t.onNext(r),t.onCompleted()):t.onCompleted(),oe}function i(){t.call(this,n),this.isDisposed=!1,this.isStopped=!1,this.value=null,this.hasValue=!1,this.observers=[],this.exception=null}return X(i,t),Y(i.prototype,xe,{hasObservers:function(){return e.call(this),this.observers.length>0},onCompleted:function(){var t,n,i;if(e.call(this),!this.isStopped){this.isStopped=!0;var r=this.observers.slice(0),s=this.value,o=this.hasValue;if(o)for(n=0,i=r.length;i>n;n++)t=r[n],t.onNext(s),t.onCompleted();else for(n=0,i=r.length;i>n;n++)r[n].onCompleted();this.observers=[]}},onError:function(t){if(e.call(this),!this.isStopped){var n=this.observers.slice(0);this.isStopped=!0,this.exception=t;for(var i=0,r=n.length;r>i;i++)n[i].onError(t);this.observers=[]}},onNext:function(t){e.call(this),this.isStopped||(this.value=t,this.hasValue=!0)},dispose:function(){this.isDisposed=!0,this.observers=null,this.exception=null,this.value=null}}),i}(Pe);var Te=function(t){function e(t){return this.observable.subscribe(t)}function n(n,i){t.call(this,e),this.observer=n,this.observable=i}return X(n,t),Y(n.prototype,xe,{onCompleted:function(){this.observer.onCompleted()},onError:function(t){this.observer.onError(t)},onNext:function(t){this.observer.onNext(t)}}),n}(Pe);"function"==typeof define&&"object"==typeof define.amd&&define.amd?(f.Rx=m,define(function(){return m})):d&&v?b?(v.exports=m).Rx=m:d.Rx=m:f.Rx=m}).call(this); \ No newline at end of file diff --git a/ajax/libs/rxjs/2.2.28/rx.experimental.js b/ajax/libs/rxjs/2.2.28/rx.experimental.js new file mode 100644 index 000000000..364954881 --- /dev/null +++ b/ajax/libs/rxjs/2.2.28/rx.experimental.js @@ -0,0 +1,471 @@ +// 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 (typeof define === 'function' && define.amd) { + define(['rx', 'exports'], function (Rx, exports) { + root.Rx = factory(root, exports, Rx); + return root.Rx; + }); + } 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, + enumerableFor = Enumerable.forEach, + immediateScheduler = Rx.Scheduler.immediate, + currentThreadScheduler = Rx.Scheduler.currentThread, + slice = Array.prototype.slice, + AsyncSubject = Rx.AsyncSubject, + Observer = Rx.Observer, + inherits = Rx.internals.inherits, + addProperties = Rx.internals.addProperties, + noop = Rx.helpers.noop, + isPromise = Rx.helpers.isPromise, + observableFromPromise = Observable.fromPromise; + + // Utilities + function argsOrArray(args, idx) { + return args.length === 1 && Array.isArray(args[idx]) ? + args[idx] : + slice.call(args); + } + + // Shim in iterator support + var $iterator$ = (typeof Symbol === 'object' && Symbol.iterator) || + '_es6shim_iterator_'; + // Firefox ships a partial implementation using the name @@iterator. + // https://bugzilla.mozilla.org/show_bug.cgi?id=907077#c14 + // So use that name if we detect it. + if (root.Set && typeof new root.Set()['@@iterator'] === 'function') { + $iterator$ = '@@iterator'; + } + var doneEnumerator = { done: true, value: undefined }; + + function enumerableWhile(condition, source) { + return new Enumerable(function () { + return new Enumerator(function () { + return condition() ? + { done: false, value: source } : + { done: true, value: undefined }; + }); + }); + } + + /** + * Returns an observable sequence that is the result of invoking the selector on the source sequence, without sharing subscriptions. + * This operator allows for a fluent style of writing queries that use the same sequence multiple times. + * + * @param {Function} selector Selector function which can use the source sequence as many times as needed, without sharing subscriptions to the source sequence. + * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. + */ + observableProto.letBind = observableProto['let'] = function (func) { + return func(this); + }; + + /** + * Determines whether an observable collection contains values. There is an alias for this method called 'ifThen' for browsers 0) { + isOwner = !isAcquired; + isAcquired = true; + } + if (isOwner) { + m.setDisposable(scheduler.scheduleRecursive(function (self) { + var work; + if (q.length > 0) { + work = q.shift(); + } else { + isAcquired = false; + return; + } + var m1 = new SingleAssignmentDisposable(); + d.add(m1); + m1.setDisposable(work.subscribe(function (x) { + observer.onNext(x); + var result = null; + try { + result = selector(x); + } catch (e) { + observer.onError(e); + } + q.push(result); + activeCount++; + ensureActive(); + }, observer.onError.bind(observer), function () { + d.remove(m1); + activeCount--; + if (activeCount === 0) { + observer.onCompleted(); + } + })); + self(); + })); + } + }; + + q.push(source); + activeCount++; + ensureActive(); + return d; + }); + }; + + /** + * Runs all observable sequences in parallel and collect their last elements. + * + * @example + * 1 - res = Rx.Observable.forkJoin([obs1, obs2]); + * 1 - res = Rx.Observable.forkJoin(obs1, obs2, ...); + * @returns {Observable} An observable sequence with an array collecting the last elements of all the input sequences. + */ + Observable.forkJoin = function () { + var allSources = argsOrArray(arguments, 0); + return new AnonymousObservable(function (subscriber) { + var count = allSources.length; + if (count === 0) { + subscriber.onCompleted(); + return disposableEmpty; + } + var group = new CompositeDisposable(), + finished = false, + hasResults = new Array(count), + hasCompleted = new Array(count), + results = new Array(count); + + for (var idx = 0; idx < count; idx++) { + (function (i) { + var source = allSources[i]; + isPromise(source) && (source = observableFromPromise(source)); + group.add( + source.subscribe( + function (value) { + if (!finished) { + hasResults[i] = true; + results[i] = value; + } + }, + function (e) { + finished = true; + subscriber.onError(e); + group.dispose(); + }, + function () { + if (!finished) { + if (!hasResults[i]) { + subscriber.onCompleted(); + return; + } + hasCompleted[i] = true; + for (var ix = 0; ix < count; ix++) { + if (!hasCompleted[ix]) { return; } + } + finished = true; + subscriber.onNext(results); + subscriber.onCompleted(); + } + })); + })(idx); + } + + return group; + }); + }; + + /** + * Runs two observable sequences in parallel and combines their last elemenets. + * + * @param {Observable} second Second observable sequence. + * @param {Function} resultSelector Result selector function to invoke with the last elements of both sequences. + * @returns {Observable} An observable sequence with the result of calling the selector function with the last elements of both input sequences. + */ + observableProto.forkJoin = function (second, resultSelector) { + var first = this; + + return new AnonymousObservable(function (observer) { + var leftStopped = false, rightStopped = false, + hasLeft = false, hasRight = false, + lastLeft, lastRight, + leftSubscription = new SingleAssignmentDisposable(), rightSubscription = new SingleAssignmentDisposable(); + + isPromise(second) && (second = observableFromPromise(second)); + + leftSubscription.setDisposable( + first.subscribe(function (left) { + hasLeft = true; + lastLeft = left; + }, function (err) { + rightSubscription.dispose(); + observer.onError(err); + }, function () { + leftStopped = true; + if (rightStopped) { + if (!hasLeft) { + observer.onCompleted(); + } else if (!hasRight) { + observer.onCompleted(); + } else { + var result; + try { + result = resultSelector(lastLeft, lastRight); + } catch (e) { + observer.onError(e); + return; + } + observer.onNext(result); + observer.onCompleted(); + } + } + }) + ); + + rightSubscription.setDisposable( + second.subscribe(function (right) { + hasRight = true; + lastRight = right; + }, function (err) { + leftSubscription.dispose(); + observer.onError(err); + }, function () { + rightStopped = true; + if (leftStopped) { + if (!hasLeft) { + observer.onCompleted(); + } else if (!hasRight) { + observer.onCompleted(); + } else { + var result; + try { + result = resultSelector(lastLeft, lastRight); + } catch (e) { + observer.onError(e); + return; + } + observer.onNext(result); + observer.onCompleted(); + } + } + }) + ); + + return new CompositeDisposable(leftSubscription, rightSubscription); + }); + }; + + /** + * Comonadic bind operator. + * @param {Function} selector A transform function to apply to each element. + * @param {Object} scheduler Scheduler used to execute the operation. If not specified, defaults to the ImmediateScheduler. + * @returns {Observable} An observable sequence which results from the comonadic bind operation. + */ + observableProto.manySelect = function (selector, scheduler) { + scheduler || (scheduler = immediateScheduler); + var source = this; + return observableDefer(function () { + var chain; + + return source + .select( + function (x) { + var curr = new ChainObservable(x); + if (chain) { + chain.onNext(x); + } + chain = curr; + + return curr; + }) + .doAction( + noop, + function (e) { + if (chain) { + chain.onError(e); + } + }, + function () { + if (chain) { + chain.onCompleted(); + } + }) + .observeOn(scheduler) + .select(function (x, i, o) { return selector(x, i, o); }); + }); + }; + + var ChainObservable = (function (_super) { + + function subscribe (observer) { + var self = this, g = new CompositeDisposable(); + g.add(currentThreadScheduler.schedule(function () { + observer.onNext(self.head); + g.add(self.tail.mergeObservable().subscribe(observer)); + })); + + return g; + } + + inherits(ChainObservable, _super); + + function ChainObservable(head) { + _super.call(this, subscribe); + this.head = head; + this.tail = new AsyncSubject(); + } + + addProperties(ChainObservable.prototype, Observer, { + onCompleted: function () { + this.onNext(Observable.empty()); + }, + onError: function (e) { + this.onNext(Observable.throwException(e)); + }, + onNext: function (v) { + this.tail.onNext(v); + this.tail.onCompleted(); + } + }); + + return ChainObservable; + + }(Observable)); + + return Rx; +})); \ No newline at end of file diff --git a/ajax/libs/rxjs/2.2.28/rx.experimental.min.js b/ajax/libs/rxjs/2.2.28/rx.experimental.min.js new file mode 100644 index 000000000..f764595ce --- /dev/null +++ b/ajax/libs/rxjs/2.2.28/rx.experimental.min.js @@ -0,0 +1 @@ +(function(t){var e={"boolean":!1,"function":!0,object:!0,number:!1,string:!1,undefined:!1},n=e[typeof window]&&window||this,r=e[typeof exports]&&exports&&!exports.nodeType&&exports,i=e[typeof module]&&module&&!module.nodeType&&module,o=(i&&i.exports===r&&r,e[typeof global]&&global);!o||o.global!==o&&o.window!==o||(n=o),"function"==typeof define&&define.amd?define(["rx","exports"],function(e,r){return n.Rx=t(n,r,e),n.Rx}):"object"==typeof module&&module&&module.exports===r?module.exports=t(n,module.exports,require("./rx")):n.Rx=t(n,{},n.Rx)}).call(this,function(t,e,n,r){function i(t,e){return 1===t.length&&Array.isArray(t[e])?t[e]:E.call(t)}function o(t,e){return new m(function(){return new v(function(){return t()?{done:!1,value:e}:{done:!0,value:r}})})}var s=n.Observable,u=s.prototype,c=n.AnonymousObservable,a=s.concat,h=s.defer,l=s.empty,f=n.Disposable.empty,p=n.CompositeDisposable,d=n.SerialDisposable,b=n.SingleAssignmentDisposable,v=n.internals.Enumerator,m=n.internals.Enumerable,y=m.forEach,w=n.Scheduler.immediate,g=n.Scheduler.currentThread,E=Array.prototype.slice,x=n.AsyncSubject,C=n.Observer,D=n.internals.inherits,S=n.internals.addProperties,N=n.helpers.noop,A=n.helpers.isPromise,_=s.fromPromise,O="object"==typeof Symbol&&Symbol.iterator||"_es6shim_iterator_";t.Set&&"function"==typeof(new t.Set)["@@iterator"]&&(O="@@iterator"),u.letBind=u.let=function(t){return t(this)},s["if"]=s.ifThen=function(t,e,n){return h(function(){return n||(n=l()),A(e)&&(e=_(e)),A(n)&&(n=_(n)),"function"==typeof n.now&&(n=l(n)),t()?e:n})},s["for"]=s.forIn=function(t,e){return y(t,e).concat()};var j=s["while"]=s.whileDo=function(t,e){return A(e)&&(e=_(e)),o(t,e).concat()};u.doWhile=function(t){return a([this,j(t,this)])},s["case"]=s.switchCase=function(t,e,n){return h(function(){n||(n=l()),"function"==typeof n.now&&(n=l(n));var r=e[t()];return A(r)&&(r=_(r)),r||n})},u.expand=function(t,e){e||(e=w);var n=this;return new c(function(i){var o=[],s=new d,u=new p(s),c=0,a=!1,h=function(){var n=!1;o.length>0&&(n=!a,a=!0),n&&s.setDisposable(e.scheduleRecursive(function(e){var n;if(!(o.length>0))return a=!1,r;n=o.shift();var s=new b;u.add(s),s.setDisposable(n.subscribe(function(e){i.onNext(e);var n=null;try{n=t(e)}catch(r){i.onError(r)}o.push(n),c++,h()},i.onError.bind(i),function(){u.remove(s),c--,0===c&&i.onCompleted()})),e()}))};return o.push(n),c++,h(),u})},s.forkJoin=function(){var t=i(arguments,0);return new c(function(e){var n=t.length;if(0===n)return e.onCompleted(),f;for(var i=new p,o=!1,s=Array(n),u=Array(n),c=Array(n),a=0;n>a;a++)(function(a){var h=t[a];A(h)&&(h=_(h)),i.add(h.subscribe(function(t){o||(s[a]=!0,c[a]=t)},function(t){o=!0,e.onError(t),i.dispose()},function(){if(!o){if(!s[a])return e.onCompleted(),r;u[a]=!0;for(var t=0;n>t;t++)if(!u[t])return;o=!0,e.onNext(c),e.onCompleted()}}))})(a);return i})},u.forkJoin=function(t,e){var n=this;return new c(function(i){var o,s,u=!1,c=!1,a=!1,h=!1,l=new b,f=new b;return A(t)&&(t=_(t)),l.setDisposable(n.subscribe(function(t){a=!0,o=t},function(t){f.dispose(),i.onError(t)},function(){if(u=!0,c)if(a)if(h){var t;try{t=e(o,s)}catch(n){return i.onError(n),r}i.onNext(t),i.onCompleted()}else i.onCompleted();else i.onCompleted()})),f.setDisposable(t.subscribe(function(t){h=!0,s=t},function(t){l.dispose(),i.onError(t)},function(){if(c=!0,u)if(a)if(h){var t;try{t=e(o,s)}catch(n){return i.onError(n),r}i.onNext(t),i.onCompleted()}else i.onCompleted();else i.onCompleted()})),new p(l,f)})},u.manySelect=function(t,e){e||(e=w);var n=this;return h(function(){var r;return n.select(function(t){var e=new R(t);return r&&r.onNext(t),r=e,e}).doAction(N,function(t){r&&r.onError(t)},function(){r&&r.onCompleted()}).observeOn(e).select(function(e,n,r){return t(e,n,r)})})};var R=function(t){function e(t){var e=this,n=new p;return n.add(g.schedule(function(){t.onNext(e.head),n.add(e.tail.mergeObservable().subscribe(t))})),n}function n(n){t.call(this,e),this.head=n,this.tail=new x}return D(n,t),S(n.prototype,C,{onCompleted:function(){this.onNext(s.empty())},onError:function(t){this.onNext(s.throwException(t))},onNext:function(t){this.tail.onNext(t),this.tail.onCompleted()}}),n}(s);return n}); \ No newline at end of file diff --git a/ajax/libs/rxjs/2.2.28/rx.joinpatterns.js b/ajax/libs/rxjs/2.2.28/rx.joinpatterns.js new file mode 100644 index 000000000..481f694c3 --- /dev/null +++ b/ajax/libs/rxjs/2.2.28/rx.joinpatterns.js @@ -0,0 +1,415 @@ +// 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 (typeof define === 'function' && define.amd) { + define(['rx', 'exports'], function (Rx, exports) { + root.Rx = factory(root, exports, Rx); + return root.Rx; + }); + } 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.throwException, + 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, + slice = Array.prototype.slice; + + // Utilities + function argsOrArray(args, idx) { + return args.length === 1 && Array.isArray(args[idx]) ? + args[idx] : + slice.call(args); + } + + /** @private */ + var Map = (function () { + + /** + * @constructor + * @private + */ + function Map() { + this.keys = []; + this.values = []; + } + + /** + * @private + * @memberOf Map# + */ + Map.prototype['delete'] = function (key) { + var i = this.keys.indexOf(key); + if (i !== -1) { + this.keys.splice(i, 1); + this.values.splice(i, 1); + } + return i !== -1; + }; + + /** + * @private + * @memberOf Map# + */ + Map.prototype.get = function (key, fallback) { + var i = this.keys.indexOf(key); + return i !== -1 ? this.values[i] : fallback; + }; + + /** + * @private + * @memberOf Map# + */ + Map.prototype.set = function (key, value) { + var i = this.keys.indexOf(key); + if (i !== -1) { + this.values[i] = value; + } + this.values[this.keys.push(key) - 1] = value; + }; + + /** + * @private + * @memberOf Map# + */ + Map.prototype.size = function () { return this.keys.length; }; + + /** + * @private + * @memberOf Map# + */ + Map.prototype.has = function (key) { + return this.keys.indexOf(key) !== -1; + }; + + /** + * @private + * @memberOf Map# + */ + Map.prototype.getKeys = function () { return this.keys.slice(0); }; + + /** + * @private + * @memberOf Map# + */ + Map.prototype.getValues = function () { return this.values.slice(0); }; + + return Map; + }()); + + /** + * @constructor + * Represents a join pattern over observable sequences. + */ + function Pattern(patterns) { + this.patterns = patterns; + } + + /** + * Creates a pattern that matches the current plan matches and when the specified observable sequences has an available value. + * + * @param other Observable sequence to match in addition to the current pattern. + * @return Pattern object that matches when all observable sequences in the pattern have an available value. + */ + Pattern.prototype.and = function (other) { + var patterns = this.patterns.slice(0); + patterns.push(other); + return new Pattern(patterns); + }; + + /** + * Matches when all observable sequences in the pattern (specified using a chain of and operators) have an available value and projects the values. + * + * @param selector Selector that will be invoked with available values from the source sequences, in the same order of the sequences in the pattern. + * @return Plan that produces the projected values, to be fed (with other plans) to the when operator. + */ + Pattern.prototype.then = function (selector) { + return new Plan(this, selector); + }; + + function Plan(expression, selector) { + this.expression = expression; + this.selector = selector; + } + + Plan.prototype.activate = function (externalSubscriptions, observer, deactivate) { + var self = this; + var joinObservers = []; + for (var i = 0, len = this.expression.patterns.length; i < len; i++) { + joinObservers.push(planCreateObserver(externalSubscriptions, this.expression.patterns[i], observer.onError.bind(observer))); + } + var activePlan = new ActivePlan(joinObservers, function () { + var result; + try { + result = self.selector.apply(self, arguments); + } catch (exception) { + observer.onError(exception); + return; + } + observer.onNext(result); + }, function () { + for (var j = 0, jlen = joinObservers.length; j < jlen; j++) { + joinObservers[j].removeActivePlan(activePlan); + } + deactivate(activePlan); + }); + for (i = 0, len = joinObservers.length; i < len; i++) { + joinObservers[i].addActivePlan(activePlan); + } + return activePlan; + }; + + function planCreateObserver(externalSubscriptions, observable, onError) { + var entry = externalSubscriptions.get(observable); + if (!entry) { + var observer = new JoinObserver(observable, onError); + externalSubscriptions.set(observable, observer); + return observer; + } + return entry; + } + + // Active Plan + function ActivePlan(joinObserverArray, onNext, onCompleted) { + var i, joinObserver; + this.joinObserverArray = joinObserverArray; + this.onNext = onNext; + this.onCompleted = onCompleted; + this.joinObservers = new Map(); + for (i = 0; i < this.joinObserverArray.length; i++) { + joinObserver = this.joinObserverArray[i]; + this.joinObservers.set(joinObserver, joinObserver); + } + } + + ActivePlan.prototype.dequeue = function () { + var values = this.joinObservers.getValues(); + for (var i = 0, len = values.length; i < len; i++) { + values[i].queue.shift(); + } + }; + ActivePlan.prototype.match = function () { + var firstValues, i, len, isCompleted, values, hasValues = true; + for (i = 0, len = this.joinObserverArray.length; i < len; i++) { + if (this.joinObserverArray[i].queue.length === 0) { + hasValues = false; + break; + } + } + if (hasValues) { + firstValues = []; + isCompleted = false; + for (i = 0, len = this.joinObserverArray.length; i < len; i++) { + firstValues.push(this.joinObserverArray[i].queue[0]); + if (this.joinObserverArray[i].queue[0].kind === 'C') { + isCompleted = true; + } + } + if (isCompleted) { + this.onCompleted(); + } else { + this.dequeue(); + values = []; + for (i = 0; i < firstValues.length; i++) { + values.push(firstValues[i].value); + } + this.onNext.apply(this, values); + } + } + }; + + /** @private */ + var JoinObserver = (function (_super) { + + inherits(JoinObserver, _super); + + /** + * @constructor + * @private + */ + function JoinObserver(source, onError) { + _super.call(this); + this.source = source; + this.onError = onError; + this.queue = []; + this.activePlans = []; + this.subscription = new SingleAssignmentDisposable(); + this.isDisposed = false; + } + + var JoinObserverPrototype = JoinObserver.prototype; + + /** + * @memberOf JoinObserver# + * @private + */ + JoinObserverPrototype.next = function (notification) { + if (!this.isDisposed) { + if (notification.kind === 'E') { + this.onError(notification.exception); + return; + } + this.queue.push(notification); + var activePlans = this.activePlans.slice(0); + for (var i = 0, len = activePlans.length; i < len; i++) { + activePlans[i].match(); + } + } + }; + + /** + * @memberOf JoinObserver# + * @private + */ + JoinObserverPrototype.error = noop; + + /** + * @memberOf JoinObserver# + * @private + */ + JoinObserverPrototype.completed = noop; + + /** + * @memberOf JoinObserver# + * @private + */ + JoinObserverPrototype.addActivePlan = function (activePlan) { + this.activePlans.push(activePlan); + }; + + /** + * @memberOf JoinObserver# + * @private + */ + JoinObserverPrototype.subscribe = function () { + this.subscription.setDisposable(this.source.materialize().subscribe(this)); + }; + + /** + * @memberOf JoinObserver# + * @private + */ + JoinObserverPrototype.removeActivePlan = function (activePlan) { + var idx = this.activePlans.indexOf(activePlan); + this.activePlans.splice(idx, 1); + if (this.activePlans.length === 0) { + this.dispose(); + } + }; + + /** + * @memberOf JoinObserver# + * @private + */ + JoinObserverPrototype.dispose = function () { + _super.prototype.dispose.call(this); + if (!this.isDisposed) { + this.isDisposed = true; + this.subscription.dispose(); + } + }; + + return JoinObserver; + } (AbstractObserver)); + + /** + * Creates a pattern that matches when both observable sequences have an available value. + * + * @param right Observable sequence to match with the current sequence. + * @return {Pattern} Pattern object that matches when both observable sequences have an available value. + */ + observableProto.and = function (right) { + return new Pattern([this, right]); + }; + + /** + * Matches when the observable sequence has an available value and projects the value. + * + * @param selector Selector that will be invoked for values in the source sequence. + * @returns {Plan} Plan that produces the projected values, to be fed (with other plans) to the when operator. + */ + observableProto.then = function (selector) { + return new Pattern([this]).then(selector); + }; + + /** + * Joins together the results from several patterns. + * + * @param plans A series of plans (specified as an Array of as a series of arguments) created by use of the Then operator on patterns. + * @returns {Observable} Observable sequence with the results form matching several patterns. + */ + Observable.when = function () { + var plans = argsOrArray(arguments, 0); + return new AnonymousObservable(function (observer) { + var activePlans = [], + externalSubscriptions = new Map(), + group, + i, len, + joinObserver, + joinValues, + outObserver; + outObserver = observerCreate(observer.onNext.bind(observer), function (exception) { + var values = externalSubscriptions.getValues(); + for (var j = 0, jlen = values.length; j < jlen; j++) { + values[j].onError(exception); + } + observer.onError(exception); + }, observer.onCompleted.bind(observer)); + try { + for (i = 0, len = plans.length; i < len; i++) { + activePlans.push(plans[i].activate(externalSubscriptions, outObserver, function (activePlan) { + var idx = activePlans.indexOf(activePlan); + activePlans.splice(idx, 1); + if (activePlans.length === 0) { + outObserver.onCompleted(); + } + })); + } + } catch (e) { + observableThrow(e).subscribe(observer); + } + group = new CompositeDisposable(); + joinValues = externalSubscriptions.getValues(); + for (i = 0, len = joinValues.length; i < len; i++) { + joinObserver = joinValues[i]; + joinObserver.subscribe(); + group.add(joinObserver); + } + return group; + }); + }; + + return Rx; +})); \ No newline at end of file diff --git a/ajax/libs/rxjs/2.2.28/rx.joinpatterns.min.js b/ajax/libs/rxjs/2.2.28/rx.joinpatterns.min.js new file mode 100644 index 000000000..924fbb33f --- /dev/null +++ b/ajax/libs/rxjs/2.2.28/rx.joinpatterns.min.js @@ -0,0 +1 @@ +(function(t){var e={"boolean":!1,"function":!0,object:!0,number:!1,string:!1,undefined:!1},n=e[typeof window]&&window||this,r=e[typeof exports]&&exports&&!exports.nodeType&&exports,i=e[typeof module]&&module&&!module.nodeType&&module,o=(i&&i.exports===r&&r,e[typeof global]&&global);!o||o.global!==o&&o.window!==o||(n=o),"function"==typeof define&&define.amd?define(["rx","exports"],function(e,r){return n.Rx=t(n,r,e),n.Rx}):"object"==typeof module&&module&&module.exports===r?module.exports=t(n,module.exports,require("./rx")):n.Rx=t(n,{},n.Rx)}).call(this,function(t,e,n){function r(t,e){return 1===t.length&&Array.isArray(t[e])?t[e]:y.call(t)}function i(t){this.patterns=t}function o(t,e){this.expression=t,this.selector=e}function s(t,e,n){var r=t.get(e);if(!r){var i=new g(e,n);return t.set(e,i),i}return r}function u(t,e,n){var r,i;for(this.joinObserverArray=t,this.onNext=e,this.onCompleted=n,this.joinObservers=new w,r=0;this.joinObserverArray.length>r;r++)i=this.joinObserverArray[r],this.joinObservers.set(i,i)}var c=n.Observable,a=c.prototype,h=n.AnonymousObservable,l=c.throwException,f=n.Observer.create,p=n.SingleAssignmentDisposable,d=n.CompositeDisposable,b=n.internals.AbstractObserver,v=n.helpers.noop,m=(n.internals.isEqual,n.internals.inherits),y=Array.prototype.slice,w=function(){function t(){this.keys=[],this.values=[]}return t.prototype["delete"]=function(t){var e=this.keys.indexOf(t);return-1!==e&&(this.keys.splice(e,1),this.values.splice(e,1)),-1!==e},t.prototype.get=function(t,e){var n=this.keys.indexOf(t);return-1!==n?this.values[n]:e},t.prototype.set=function(t,e){var n=this.keys.indexOf(t);-1!==n&&(this.values[n]=e),this.values[this.keys.push(t)-1]=e},t.prototype.size=function(){return this.keys.length},t.prototype.has=function(t){return-1!==this.keys.indexOf(t)},t.prototype.getKeys=function(){return this.keys.slice(0)},t.prototype.getValues=function(){return this.values.slice(0)},t}();i.prototype.and=function(t){var e=this.patterns.slice(0);return e.push(t),new i(e)},i.prototype.then=function(t){return new o(this,t)},o.prototype.activate=function(t,e,n){for(var r=this,i=[],o=0,c=this.expression.patterns.length;c>o;o++)i.push(s(t,this.expression.patterns[o],e.onError.bind(e)));var a=new u(i,function(){var t;try{t=r.selector.apply(r,arguments)}catch(n){return e.onError(n),undefined}e.onNext(t)},function(){for(var t=0,e=i.length;e>t;t++)i[t].removeActivePlan(a);n(a)});for(o=0,c=i.length;c>o;o++)i[o].addActivePlan(a);return a},u.prototype.dequeue=function(){for(var t=this.joinObservers.getValues(),e=0,n=t.length;n>e;e++)t[e].queue.shift()},u.prototype.match=function(){var t,e,n,r,i,o=!0;for(e=0,n=this.joinObserverArray.length;n>e;e++)if(0===this.joinObserverArray[e].queue.length){o=!1;break}if(o){for(t=[],r=!1,e=0,n=this.joinObserverArray.length;n>e;e++)t.push(this.joinObserverArray[e].queue[0]),"C"===this.joinObserverArray[e].queue[0].kind&&(r=!0);if(r)this.onCompleted();else{for(this.dequeue(),i=[],e=0;t.length>e;e++)i.push(t[e].value);this.onNext.apply(this,i)}}};var g=function(t){function e(e,n){t.call(this),this.source=e,this.onError=n,this.queue=[],this.activePlans=[],this.subscription=new p,this.isDisposed=!1}m(e,t);var n=e.prototype;return n.next=function(t){if(!this.isDisposed){if("E"===t.kind)return this.onError(t.exception),undefined;this.queue.push(t);for(var e=this.activePlans.slice(0),n=0,r=e.length;r>n;n++)e[n].match()}},n.error=v,n.completed=v,n.addActivePlan=function(t){this.activePlans.push(t)},n.subscribe=function(){this.subscription.setDisposable(this.source.materialize().subscribe(this))},n.removeActivePlan=function(t){var e=this.activePlans.indexOf(t);this.activePlans.splice(e,1),0===this.activePlans.length&&this.dispose()},n.dispose=function(){t.prototype.dispose.call(this),this.isDisposed||(this.isDisposed=!0,this.subscription.dispose())},e}(b);return a.and=function(t){return new i([this,t])},a.then=function(t){return new i([this]).then(t)},c.when=function(){var t=r(arguments,0);return new h(function(e){var n,r,i,o,s,u,c=[],a=new w;u=f(e.onNext.bind(e),function(t){for(var n=a.getValues(),r=0,i=n.length;i>r;r++)n[r].onError(t);e.onError(t)},e.onCompleted.bind(e));try{for(r=0,i=t.length;i>r;r++)c.push(t[r].activate(a,u,function(t){var e=c.indexOf(t);c.splice(e,1),0===c.length&&u.onCompleted()}))}catch(h){l(h).subscribe(e)}for(n=new d,s=a.getValues(),r=0,i=s.length;i>r;r++)o=s[r],o.subscribe(),n.add(o);return n})},n}); \ No newline at end of file diff --git a/ajax/libs/rxjs/2.2.28/rx.js b/ajax/libs/rxjs/2.2.28/rx.js new file mode 100644 index 000000000..0a8a76a7b --- /dev/null +++ b/ajax/libs/rxjs/2.2.28/rx.js @@ -0,0 +1,4640 @@ +// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. + +;(function (undefined) { + + var objectTypes = { + 'boolean': false, + 'function': true, + 'object': true, + 'number': false, + 'string': false, + 'undefined': false + }; + + var root = (objectTypes[typeof window] && window) || this, + freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports, + freeModule = objectTypes[typeof module] && module && !module.nodeType && module, + moduleExports = freeModule && freeModule.exports === freeExports && freeExports, + freeGlobal = objectTypes[typeof global] && global; + + if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal)) { + root = freeGlobal; + } + + var Rx = { + internals: {}, + config: { + Promise: root.Promise // Detect if promise exists + }, + helpers: { } + }; + + // Defaults + var noop = Rx.helpers.noop = function () { }, + identity = Rx.helpers.identity = function (x) { return x; }, + pluck = Rx.helpers.pluck = function (property) { return function (x) { return x[property]; }; }, + just = Rx.helpers.just = function (value) { return function () { return value; }; }, + defaultNow = Rx.helpers.defaultNow = Date.now, + defaultComparer = Rx.helpers.defaultComparer = function (x, y) { return isEqual(x, y); }, + defaultSubComparer = Rx.helpers.defaultSubComparer = function (x, y) { return x > y ? 1 : (x < y ? -1 : 0); }, + defaultKeySerializer = Rx.helpers.defaultKeySerializer = function (x) { return x.toString(); }, + defaultError = Rx.helpers.defaultError = function (err) { throw err; }, + isPromise = Rx.helpers.isPromise = function (p) { return !!p && typeof p.then === 'function' && p.then !== Rx.Observable.prototype.then; }, + asArray = Rx.helpers.asArray = function () { return Array.prototype.slice.call(arguments); }, + not = Rx.helpers.not = function (a) { return !a; }; + + // Errors + var sequenceContainsNoElements = 'Sequence contains no elements.'; + var argumentOutOfRange = 'Argument out of range'; + var objectDisposed = 'Object has been disposed'; + function checkDisposed() { if (this.isDisposed) { throw new Error(objectDisposed); } } + + // Shim in iterator support + var $iterator$ = (typeof Symbol === 'object' && Symbol.iterator) || + '_es6shim_iterator_'; + // Firefox ships a partial implementation using the name @@iterator. + // https://bugzilla.mozilla.org/show_bug.cgi?id=907077#c14 + // So use that name if we detect it. + if (root.Set && typeof new root.Set()['@@iterator'] === 'function') { + $iterator$ = '@@iterator'; + } + var doneEnumerator = { done: true, value: undefined }; + + /** `Object#toString` result shortcuts */ + var argsClass = '[object Arguments]', + arrayClass = '[object Array]', + boolClass = '[object Boolean]', + dateClass = '[object Date]', + errorClass = '[object Error]', + funcClass = '[object Function]', + numberClass = '[object Number]', + objectClass = '[object Object]', + regexpClass = '[object RegExp]', + stringClass = '[object String]'; + + var toString = Object.prototype.toString, + hasOwnProperty = Object.prototype.hasOwnProperty, + supportsArgsClass = toString.call(arguments) == argsClass, // For less -1); + } + }); + } + } + stackA.pop(); + stackB.pop(); + + return result; + } + var slice = Array.prototype.slice; + function argsOrArray(args, idx) { + return args.length === 1 && Array.isArray(args[idx]) ? + args[idx] : + slice.call(args); + } + var hasProp = {}.hasOwnProperty; + + /** @private */ + var inherits = this.inherits = Rx.internals.inherits = function (child, parent) { + function __() { this.constructor = child; } + __.prototype = parent.prototype; + child.prototype = new __(); + }; + + /** @private */ + var addProperties = Rx.internals.addProperties = function (obj) { + var sources = slice.call(arguments, 1); + for (var i = 0, len = sources.length; i < len; i++) { + var source = sources[i]; + for (var prop in source) { + obj[prop] = source[prop]; + } + } + }; + + // Rx Utils + var addRef = Rx.internals.addRef = function (xs, r) { + return new AnonymousObservable(function (observer) { + return new CompositeDisposable(r.getDisposable(), xs.subscribe(observer)); + }); + }; + + // Collection polyfills + function arrayInitialize(count, factory) { + var a = new Array(count); + for (var i = 0; i < count; i++) { + a[i] = factory(); + } + return a; + } + + // Collections + var IndexedItem = function (id, value) { + this.id = id; + this.value = value; + }; + + IndexedItem.prototype.compareTo = function (other) { + var c = this.value.compareTo(other.value); + if (c === 0) { + c = this.id - other.id; + } + return c; + }; + + // Priority Queue for Scheduling + var PriorityQueue = Rx.internals.PriorityQueue = function (capacity) { + this.items = new Array(capacity); + this.length = 0; + }; + + var priorityProto = PriorityQueue.prototype; + priorityProto.isHigherPriority = function (left, right) { + return this.items[left].compareTo(this.items[right]) < 0; + }; + + priorityProto.percolate = function (index) { + if (index >= this.length || index < 0) { + return; + } + var parent = index - 1 >> 1; + if (parent < 0 || parent === index) { + return; + } + if (this.isHigherPriority(index, parent)) { + var temp = this.items[index]; + this.items[index] = this.items[parent]; + this.items[parent] = temp; + this.percolate(parent); + } + }; + + priorityProto.heapify = function (index) { + if (index === undefined) { + index = 0; + } + if (index >= this.length || index < 0) { + return; + } + var left = 2 * index + 1, + right = 2 * index + 2, + first = index; + if (left < this.length && this.isHigherPriority(left, first)) { + first = left; + } + if (right < this.length && this.isHigherPriority(right, first)) { + first = right; + } + if (first !== index) { + var temp = this.items[index]; + this.items[index] = this.items[first]; + this.items[first] = temp; + this.heapify(first); + } + }; + + priorityProto.peek = function () { return this.items[0].value; }; + + priorityProto.removeAt = function (index) { + this.items[index] = this.items[--this.length]; + delete this.items[this.length]; + this.heapify(); + }; + + priorityProto.dequeue = function () { + var result = this.peek(); + this.removeAt(0); + return result; + }; + + priorityProto.enqueue = function (item) { + var index = this.length++; + this.items[index] = new IndexedItem(PriorityQueue.count++, item); + this.percolate(index); + }; + + priorityProto.remove = function (item) { + for (var i = 0; i < this.length; i++) { + if (this.items[i].value === item) { + this.removeAt(i); + return true; + } + } + return false; + }; + PriorityQueue.count = 0; + /** + * Represents a group of disposable resources that are disposed together. + * @constructor + */ + var CompositeDisposable = Rx.CompositeDisposable = function () { + this.disposables = argsOrArray(arguments, 0); + this.isDisposed = false; + this.length = this.disposables.length; + }; + + var CompositeDisposablePrototype = CompositeDisposable.prototype; + + /** + * Adds a disposable to the CompositeDisposable or disposes the disposable if the CompositeDisposable is disposed. + * @param {Mixed} item Disposable to add. + */ + CompositeDisposablePrototype.add = function (item) { + if (this.isDisposed) { + item.dispose(); + } else { + this.disposables.push(item); + this.length++; + } + }; + + /** + * Removes and disposes the first occurrence of a disposable from the CompositeDisposable. + * @param {Mixed} item Disposable to remove. + * @returns {Boolean} true if found; false otherwise. + */ + CompositeDisposablePrototype.remove = function (item) { + var shouldDispose = false; + if (!this.isDisposed) { + var idx = this.disposables.indexOf(item); + if (idx !== -1) { + shouldDispose = true; + this.disposables.splice(idx, 1); + this.length--; + item.dispose(); + } + + } + return shouldDispose; + }; + + /** + * Disposes all disposables in the group and removes them from the group. + */ + CompositeDisposablePrototype.dispose = function () { + if (!this.isDisposed) { + this.isDisposed = true; + var currentDisposables = this.disposables.slice(0); + this.disposables = []; + this.length = 0; + + for (var i = 0, len = currentDisposables.length; i < len; i++) { + currentDisposables[i].dispose(); + } + } + }; + + /** + * Removes and disposes all disposables from the CompositeDisposable, but does not dispose the CompositeDisposable. + */ + CompositeDisposablePrototype.clear = function () { + var currentDisposables = this.disposables.slice(0); + this.disposables = []; + this.length = 0; + for (var i = 0, len = currentDisposables.length; i < len; i++) { + currentDisposables[i].dispose(); + } + }; + + /** + * Determines whether the CompositeDisposable contains a specific disposable. + * @param {Mixed} item Disposable to search for. + * @returns {Boolean} true if the disposable was found; otherwise, false. + */ + CompositeDisposablePrototype.contains = function (item) { + return this.disposables.indexOf(item) !== -1; + }; + + /** + * Converts the existing CompositeDisposable to an array of disposables + * @returns {Array} An array of disposable objects. + */ + CompositeDisposablePrototype.toArray = function () { + return this.disposables.slice(0); + }; + + /** + * Provides a set of static methods for creating Disposables. + * + * @constructor + * @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once. + */ + var Disposable = Rx.Disposable = function (action) { + this.isDisposed = false; + this.action = action || noop; + }; + + /** Performs the task of cleaning up resources. */ + Disposable.prototype.dispose = function () { + if (!this.isDisposed) { + this.action(); + this.isDisposed = true; + } + }; + + /** + * Creates a disposable object that invokes the specified action when disposed. + * @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once. + * @return {Disposable} The disposable object that runs the given action upon disposal. + */ + var disposableCreate = Disposable.create = function (action) { return new Disposable(action); }; + + /** + * Gets the disposable that does nothing when disposed. + */ + var disposableEmpty = Disposable.empty = { dispose: noop }; + + var BooleanDisposable = (function () { + function BooleanDisposable (isSingle) { + this.isSingle = isSingle; + this.isDisposed = false; + this.current = null; + } + + var booleanDisposablePrototype = BooleanDisposable.prototype; + + /** + * Gets the underlying disposable. + * @return The underlying disposable. + */ + booleanDisposablePrototype.getDisposable = function () { + return this.current; + }; + + /** + * Sets the underlying disposable. + * @param {Disposable} value The new underlying disposable. + */ + booleanDisposablePrototype.setDisposable = function (value) { + if (this.current && this.isSingle) { + throw new Error('Disposable has already been assigned'); + } + + var shouldDispose = this.isDisposed, old; + if (!shouldDispose) { + old = this.current; + this.current = value; + } + if (old) { + old.dispose(); + } + if (shouldDispose && value) { + value.dispose(); + } + }; + + /** + * Disposes the underlying disposable as well as all future replacements. + */ + booleanDisposablePrototype.dispose = function () { + var old; + if (!this.isDisposed) { + this.isDisposed = true; + old = this.current; + this.current = null; + } + if (old) { + old.dispose(); + } + }; + + return BooleanDisposable; + }()); + + /** + * Represents a disposable resource which only allows a single assignment of its underlying disposable resource. + * If an underlying disposable resource has already been set, future attempts to set the underlying disposable resource will throw an Error. + */ + var SingleAssignmentDisposable = Rx.SingleAssignmentDisposable = (function (super_) { + inherits(SingleAssignmentDisposable, super_); + + function SingleAssignmentDisposable() { + super_.call(this, true); + } + + return SingleAssignmentDisposable; + }(BooleanDisposable)); + + /** + * Represents a disposable resource whose underlying disposable resource can be replaced by another disposable resource, causing automatic disposal of the previous underlying disposable resource. + */ + var SerialDisposable = Rx.SerialDisposable = (function (super_) { + inherits(SerialDisposable, super_); + + function SerialDisposable() { + super_.call(this, false); + } + + return SerialDisposable; + }(BooleanDisposable)); + + /** + * Represents a disposable resource that only disposes its underlying disposable resource when all dependent disposable objects have been disposed. + */ + var RefCountDisposable = Rx.RefCountDisposable = (function () { + + function InnerDisposable(disposable) { + this.disposable = disposable; + this.disposable.count++; + this.isInnerDisposed = false; + } + + InnerDisposable.prototype.dispose = function () { + if (!this.disposable.isDisposed) { + if (!this.isInnerDisposed) { + this.isInnerDisposed = true; + this.disposable.count--; + if (this.disposable.count === 0 && this.disposable.isPrimaryDisposed) { + this.disposable.isDisposed = true; + this.disposable.underlyingDisposable.dispose(); + } + } + } + }; + + /** + * Initializes a new instance of the RefCountDisposable with the specified disposable. + * @constructor + * @param {Disposable} disposable Underlying disposable. + */ + function RefCountDisposable(disposable) { + this.underlyingDisposable = disposable; + this.isDisposed = false; + this.isPrimaryDisposed = false; + this.count = 0; + } + + /** + * Disposes the underlying disposable only when all dependent disposables have been disposed + */ + RefCountDisposable.prototype.dispose = function () { + if (!this.isDisposed) { + if (!this.isPrimaryDisposed) { + this.isPrimaryDisposed = true; + if (this.count === 0) { + this.isDisposed = true; + this.underlyingDisposable.dispose(); + } + } + } + }; + + /** + * Returns a dependent disposable that when disposed decreases the refcount on the underlying disposable. + * @returns {Disposable} A dependent disposable contributing to the reference count that manages the underlying disposable's lifetime. + */ + RefCountDisposable.prototype.getDisposable = function () { + return this.isDisposed ? disposableEmpty : new InnerDisposable(this); + }; + + return RefCountDisposable; + })(); + + function ScheduledDisposable(scheduler, disposable) { + this.scheduler = scheduler; + this.disposable = disposable; + this.isDisposed = false; + } + + ScheduledDisposable.prototype.dispose = function () { + var parent = this; + this.scheduler.schedule(function () { + if (!parent.isDisposed) { + parent.isDisposed = true; + parent.disposable.dispose(); + } + }); + }; + + var ScheduledItem = Rx.internals.ScheduledItem = function (scheduler, state, action, dueTime, comparer) { + this.scheduler = scheduler; + this.state = state; + this.action = action; + this.dueTime = dueTime; + this.comparer = comparer || defaultSubComparer; + this.disposable = new SingleAssignmentDisposable(); + } + + ScheduledItem.prototype.invoke = function () { + this.disposable.setDisposable(this.invokeCore()); + }; + + ScheduledItem.prototype.compareTo = function (other) { + return this.comparer(this.dueTime, other.dueTime); + }; + + ScheduledItem.prototype.isCancelled = function () { + return this.disposable.isDisposed; + }; + + ScheduledItem.prototype.invokeCore = function () { + return this.action(this.scheduler, this.state); + }; + + /** Provides a set of static properties to access commonly used schedulers. */ + var Scheduler = Rx.Scheduler = (function () { + + /** + * @constructor + * @private + */ + function Scheduler(now, schedule, scheduleRelative, scheduleAbsolute) { + this.now = now; + this._schedule = schedule; + this._scheduleRelative = scheduleRelative; + this._scheduleAbsolute = scheduleAbsolute; + } + + function invokeRecImmediate(scheduler, pair) { + var state = pair.first, action = pair.second, group = new CompositeDisposable(), + recursiveAction = function (state1) { + action(state1, function (state2) { + var isAdded = false, isDone = false, + d = scheduler.scheduleWithState(state2, function (scheduler1, state3) { + if (isAdded) { + group.remove(d); + } else { + isDone = true; + } + recursiveAction(state3); + return disposableEmpty; + }); + if (!isDone) { + group.add(d); + isAdded = true; + } + }); + }; + recursiveAction(state); + return group; + } + + function invokeRecDate(scheduler, pair, method) { + var state = pair.first, action = pair.second, group = new CompositeDisposable(), + recursiveAction = function (state1) { + action(state1, function (state2, dueTime1) { + var isAdded = false, isDone = false, + d = scheduler[method].call(scheduler, state2, dueTime1, function (scheduler1, state3) { + if (isAdded) { + group.remove(d); + } else { + isDone = true; + } + recursiveAction(state3); + return disposableEmpty; + }); + if (!isDone) { + group.add(d); + isAdded = true; + } + }); + }; + recursiveAction(state); + return group; + } + + function invokeAction(scheduler, action) { + action(); + return disposableEmpty; + } + + var schedulerProto = Scheduler.prototype; + + /** + * Returns a scheduler that wraps the original scheduler, adding exception handling for scheduled actions. + * @param {Function} handler Handler that's run if an exception is caught. The exception will be rethrown if the handler returns false. + * @returns {Scheduler} Wrapper around the original scheduler, enforcing exception handling. + */ + schedulerProto.catchException = schedulerProto['catch'] = function (handler) { + return new CatchScheduler(this, handler); + }; + + /** + * Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation. + * @param {Number} period Period for running the work periodically. + * @param {Function} action Action to be executed. + * @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort). + */ + schedulerProto.schedulePeriodic = function (period, action) { + return this.schedulePeriodicWithState(null, period, function () { + action(); + }); + }; + + /** + * Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation. + * @param {Mixed} state Initial state passed to the action upon the first iteration. + * @param {Number} period Period for running the work periodically. + * @param {Function} action Action to be executed, potentially updating the state. + * @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort). + */ + schedulerProto.schedulePeriodicWithState = function (state, period, action) { + var s = state, id = setInterval(function () { + s = action(s); + }, period); + return disposableCreate(function () { + clearInterval(id); + }); + }; + + /** + * Schedules an action to be executed. + * @param {Function} action Action to execute. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.schedule = function (action) { + return this._schedule(action, invokeAction); + }; + + /** + * Schedules an action to be executed. + * @param state State passed to the action to be executed. + * @param {Function} action Action to be executed. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleWithState = function (state, action) { + return this._schedule(state, action); + }; + + /** + * Schedules an action to be executed after the specified relative due time. + * @param {Function} action Action to execute. + * @param {Number} dueTime Relative time after which to execute the action. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleWithRelative = function (dueTime, action) { + return this._scheduleRelative(action, dueTime, invokeAction); + }; + + /** + * Schedules an action to be executed after dueTime. + * @param state State passed to the action to be executed. + * @param {Function} action Action to be executed. + * @param {Number} dueTime Relative time after which to execute the action. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleWithRelativeAndState = function (state, dueTime, action) { + return this._scheduleRelative(state, dueTime, action); + }; + + /** + * Schedules an action to be executed at the specified absolute due time. + * @param {Function} action Action to execute. + * @param {Number} dueTime Absolute time at which to execute the action. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleWithAbsolute = function (dueTime, action) { + return this._scheduleAbsolute(action, dueTime, invokeAction); + }; + + /** + * Schedules an action to be executed at dueTime. + * @param {Mixed} state State passed to the action to be executed. + * @param {Function} action Action to be executed. + * @param {Number}dueTime Absolute time at which to execute the action. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleWithAbsoluteAndState = function (state, dueTime, action) { + return this._scheduleAbsolute(state, dueTime, action); + }; + + /** + * Schedules an action to be executed recursively. + * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleRecursive = function (action) { + return this.scheduleRecursiveWithState(action, function (_action, self) { + _action(function () { + self(_action); + }); + }); + }; + + /** + * Schedules an action to be executed recursively. + * @param {Mixed} state State passed to the action to be executed. + * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in recursive invocation state. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleRecursiveWithState = function (state, action) { + return this.scheduleWithState({ first: state, second: action }, function (s, p) { + return invokeRecImmediate(s, p); + }); + }; + + /** + * Schedules an action to be executed recursively after a specified relative due time. + * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified relative time. + * @param {Number}dueTime Relative time after which to execute the action for the first time. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleRecursiveWithRelative = function (dueTime, action) { + return this.scheduleRecursiveWithRelativeAndState(action, dueTime, function (_action, self) { + _action(function (dt) { + self(_action, dt); + }); + }); + }; + + /** + * Schedules an action to be executed recursively after a specified relative due time. + * @param {Mixed} state State passed to the action to be executed. + * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state. + * @param {Number}dueTime Relative time after which to execute the action for the first time. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleRecursiveWithRelativeAndState = function (state, dueTime, action) { + return this._scheduleRelative({ first: state, second: action }, dueTime, function (s, p) { + return invokeRecDate(s, p, 'scheduleWithRelativeAndState'); + }); + }; + + /** + * Schedules an action to be executed recursively at a specified absolute due time. + * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified absolute time. + * @param {Number}dueTime Absolute time at which to execute the action for the first time. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleRecursiveWithAbsolute = function (dueTime, action) { + return this.scheduleRecursiveWithAbsoluteAndState(action, dueTime, function (_action, self) { + _action(function (dt) { + self(_action, dt); + }); + }); + }; + + /** + * Schedules an action to be executed recursively at a specified absolute due time. + * @param {Mixed} state State passed to the action to be executed. + * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state. + * @param {Number}dueTime Absolute time at which to execute the action for the first time. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleRecursiveWithAbsoluteAndState = function (state, dueTime, action) { + return this._scheduleAbsolute({ first: state, second: action }, dueTime, function (s, p) { + return invokeRecDate(s, p, 'scheduleWithAbsoluteAndState'); + }); + }; + + /** Gets the current time according to the local machine's system clock. */ + Scheduler.now = defaultNow; + + /** + * Normalizes the specified TimeSpan value to a positive value. + * @param {Number} timeSpan The time span value to normalize. + * @returns {Number} The specified TimeSpan value if it is zero or positive; otherwise, 0 + */ + Scheduler.normalize = function (timeSpan) { + if (timeSpan < 0) { + timeSpan = 0; + } + return timeSpan; + }; + + return Scheduler; + }()); + + var normalizeTime = Scheduler.normalize; + + var SchedulePeriodicRecursive = Rx.internals.SchedulePeriodicRecursive = (function () { + function tick(command, recurse) { + recurse(0, this._period); + try { + this._state = this._action(this._state); + } catch (e) { + this._cancel.dispose(); + throw e; + } + } + + function SchedulePeriodicRecursive(scheduler, state, period, action) { + this._scheduler = scheduler; + this._state = state; + this._period = period; + this._action = action; + } + + SchedulePeriodicRecursive.prototype.start = function () { + var d = new SingleAssignmentDisposable(); + this._cancel = d; + d.setDisposable(this._scheduler.scheduleRecursiveWithRelativeAndState(0, this._period, tick.bind(this))); + + return d; + }; + + return SchedulePeriodicRecursive; + }()); + + /** + * Gets a scheduler that schedules work immediately on the current thread. + */ + var immediateScheduler = Scheduler.immediate = (function () { + + function scheduleNow(state, action) { return action(this, state); } + + function scheduleRelative(state, dueTime, action) { + var dt = normalizeTime(dt); + while (dt - this.now() > 0) { } + return action(this, state); + } + + function scheduleAbsolute(state, dueTime, action) { + return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); + } + + return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); + }()); + + /** + * Gets a scheduler that schedules work as soon as possible on the current thread. + */ + var currentThreadScheduler = Scheduler.currentThread = (function () { + var queue; + + function runTrampoline (q) { + var item; + while (q.length > 0) { + item = q.dequeue(); + if (!item.isCancelled()) { + // Note, do not schedule blocking work! + while (item.dueTime - Scheduler.now() > 0) { + } + if (!item.isCancelled()) { + item.invoke(); + } + } + } + } + + function scheduleNow(state, action) { + return this.scheduleWithRelativeAndState(state, 0, action); + } + + function scheduleRelative(state, dueTime, action) { + var dt = this.now() + Scheduler.normalize(dueTime), + si = new ScheduledItem(this, state, action, dt), + t; + if (!queue) { + queue = new PriorityQueue(4); + queue.enqueue(si); + try { + runTrampoline(queue); + } catch (e) { + throw e; + } finally { + queue = null; + } + } else { + queue.enqueue(si); + } + return si.disposable; + } + + function scheduleAbsolute(state, dueTime, action) { + return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); + } + + var currentScheduler = new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); + currentScheduler.scheduleRequired = function () { return queue === null; }; + currentScheduler.ensureTrampoline = function (action) { + if (queue === null) { + return this.schedule(action); + } else { + return action(); + } + }; + + return currentScheduler; + }()); + + + var scheduleMethod, clearMethod = noop; + (function () { + + var reNative = RegExp('^' + + String(toString) + .replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + .replace(/toString| for [^\]]+/g, '.*?') + '$' + ); + + var setImmediate = typeof (setImmediate = freeGlobal && moduleExports && freeGlobal.setImmediate) == 'function' && + !reNative.test(setImmediate) && setImmediate, + clearImmediate = typeof (clearImmediate = freeGlobal && moduleExports && freeGlobal.clearImmediate) == 'function' && + !reNative.test(clearImmediate) && clearImmediate; + + function postMessageSupported () { + // Ensure not in a worker + if (!root.postMessage || root.importScripts) { return false; } + var isAsync = false, + oldHandler = root.onmessage; + // Test for async + root.onmessage = function () { isAsync = true; }; + root.postMessage('','*'); + root.onmessage = oldHandler; + + return isAsync; + } + + // Use in order, nextTick, setImmediate, postMessage, MessageChannel, script readystatechanged, setTimeout + if (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]') { + scheduleMethod = process.nextTick; + } else if (typeof setImmediate === 'function') { + scheduleMethod = setImmediate; + clearMethod = clearImmediate; + } else if (postMessageSupported()) { + var MSG_PREFIX = 'ms.rx.schedule' + Math.random(), + tasks = {}, + taskId = 0; + + function onGlobalPostMessage(event) { + // Only if we're a match to avoid any other global events + if (typeof event.data === 'string' && event.data.substring(0, MSG_PREFIX.length) === MSG_PREFIX) { + var handleId = event.data.substring(MSG_PREFIX.length), + action = tasks[handleId]; + action(); + delete tasks[handleId]; + } + } + + if (root.addEventListener) { + root.addEventListener('message', onGlobalPostMessage, false); + } else { + root.attachEvent('onmessage', onGlobalPostMessage, false); + } + + scheduleMethod = function (action) { + var currentId = taskId++; + tasks[currentId] = action; + root.postMessage(MSG_PREFIX + currentId, '*'); + }; + } else if (!!root.MessageChannel) { + var channel = new root.MessageChannel(), + channelTasks = {}, + channelTaskId = 0; + + channel.port1.onmessage = function (event) { + var id = event.data, + action = channelTasks[id]; + action(); + delete channelTasks[id]; + }; + + scheduleMethod = function (action) { + var id = channelTaskId++; + channelTasks[id] = action; + channel.port2.postMessage(id); + }; + } else if ('document' in root && 'onreadystatechange' in root.document.createElement('script')) { + + scheduleMethod = function (action) { + var scriptElement = root.document.createElement('script'); + scriptElement.onreadystatechange = function () { + action(); + scriptElement.onreadystatechange = null; + scriptElement.parentNode.removeChild(scriptElement); + scriptElement = null; + }; + root.document.documentElement.appendChild(scriptElement); + }; + + } else { + scheduleMethod = function (action) { return setTimeout(action, 0); }; + clearMethod = clearTimeout; + } + }()); + + /** + * Gets a scheduler that schedules work via a timed callback based upon platform. + */ + var timeoutScheduler = Scheduler.timeout = (function () { + + function scheduleNow(state, action) { + var scheduler = this, + disposable = new SingleAssignmentDisposable(); + var id = scheduleMethod(function () { + if (!disposable.isDisposed) { + disposable.setDisposable(action(scheduler, state)); + } + }); + return new CompositeDisposable(disposable, disposableCreate(function () { + clearMethod(id); + })); + } + + function scheduleRelative(state, dueTime, action) { + var scheduler = this, + dt = Scheduler.normalize(dueTime); + if (dt === 0) { + return scheduler.scheduleWithState(state, action); + } + var disposable = new SingleAssignmentDisposable(); + var id = setTimeout(function () { + if (!disposable.isDisposed) { + disposable.setDisposable(action(scheduler, state)); + } + }, dt); + return new CompositeDisposable(disposable, disposableCreate(function () { + clearTimeout(id); + })); + } + + function scheduleAbsolute(state, dueTime, action) { + return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); + } + + return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); + })(); + + /** @private */ + var CatchScheduler = (function (_super) { + + function localNow() { + return this._scheduler.now(); + } + + function scheduleNow(state, action) { + return this._scheduler.scheduleWithState(state, this._wrap(action)); + } + + function scheduleRelative(state, dueTime, action) { + return this._scheduler.scheduleWithRelativeAndState(state, dueTime, this._wrap(action)); + } + + function scheduleAbsolute(state, dueTime, action) { + return this._scheduler.scheduleWithAbsoluteAndState(state, dueTime, this._wrap(action)); + } + + inherits(CatchScheduler, _super); + + /** @private */ + function CatchScheduler(scheduler, handler) { + this._scheduler = scheduler; + this._handler = handler; + this._recursiveOriginal = null; + this._recursiveWrapper = null; + _super.call(this, localNow, scheduleNow, scheduleRelative, scheduleAbsolute); + } + + /** @private */ + CatchScheduler.prototype._clone = function (scheduler) { + return new CatchScheduler(scheduler, this._handler); + }; + + /** @private */ + CatchScheduler.prototype._wrap = function (action) { + var parent = this; + return function (self, state) { + try { + return action(parent._getRecursiveWrapper(self), state); + } catch (e) { + if (!parent._handler(e)) { throw e; } + return disposableEmpty; + } + }; + }; + + /** @private */ + CatchScheduler.prototype._getRecursiveWrapper = function (scheduler) { + if (this._recursiveOriginal !== scheduler) { + this._recursiveOriginal = scheduler; + var wrapper = this._clone(scheduler); + wrapper._recursiveOriginal = scheduler; + wrapper._recursiveWrapper = wrapper; + this._recursiveWrapper = wrapper; + } + return this._recursiveWrapper; + }; + + /** @private */ + CatchScheduler.prototype.schedulePeriodicWithState = function (state, period, action) { + var self = this, failed = false, d = new SingleAssignmentDisposable(); + + d.setDisposable(this._scheduler.schedulePeriodicWithState(state, period, function (state1) { + if (failed) { return null; } + try { + return action(state1); + } catch (e) { + failed = true; + if (!self._handler(e)) { throw e; } + d.dispose(); + return null; + } + })); + + return d; + }; + + return CatchScheduler; + }(Scheduler)); + + /** + * Represents a notification to an observer. + */ + var Notification = Rx.Notification = (function () { + function Notification(kind, hasValue) { + this.hasValue = hasValue == null ? false : hasValue; + this.kind = kind; + } + + var NotificationPrototype = Notification.prototype; + + /** + * Invokes the delegate corresponding to the notification or the observer's method corresponding to the notification and returns the produced result. + * + * @memberOf Notification + * @param {Any} observerOrOnNext Delegate to invoke for an OnNext notification or Observer to invoke the notification on.. + * @param {Function} onError Delegate to invoke for an OnError notification. + * @param {Function} onCompleted Delegate to invoke for an OnCompleted notification. + * @returns {Any} Result produced by the observation. + */ + NotificationPrototype.accept = function (observerOrOnNext, onError, onCompleted) { + if (arguments.length === 1 && typeof observerOrOnNext === 'object') { + return this._acceptObservable(observerOrOnNext); + } + return this._accept(observerOrOnNext, onError, onCompleted); + }; + + /** + * Returns an observable sequence with a single notification. + * + * @memberOf Notification + * @param {Scheduler} [scheduler] Scheduler to send out the notification calls on. + * @returns {Observable} The observable sequence that surfaces the behavior of the notification upon subscription. + */ + NotificationPrototype.toObservable = function (scheduler) { + var notification = this; + scheduler || (scheduler = immediateScheduler); + return new AnonymousObservable(function (observer) { + return scheduler.schedule(function () { + notification._acceptObservable(observer); + if (notification.kind === 'N') { + observer.onCompleted(); + } + }); + }); + }; + + return Notification; + })(); + + /** + * Creates an object that represents an OnNext notification to an observer. + * @param {Any} value The value contained in the notification. + * @returns {Notification} The OnNext notification containing the value. + */ + var notificationCreateOnNext = Notification.createOnNext = (function () { + + function _accept (onNext) { + return onNext(this.value); + } + + function _acceptObservable(observer) { + return observer.onNext(this.value); + } + + function toString () { + return 'OnNext(' + this.value + ')'; + } + + return function (value) { + var notification = new Notification('N', true); + notification.value = value; + notification._accept = _accept; + notification._acceptObservable = _acceptObservable; + notification.toString = toString; + return notification; + }; + }()); + + /** + * Creates an object that represents an OnError notification to an observer. + * @param {Any} error The exception contained in the notification. + * @returns {Notification} The OnError notification containing the exception. + */ + var notificationCreateOnError = Notification.createOnError = (function () { + + function _accept (onNext, onError) { + return onError(this.exception); + } + + function _acceptObservable(observer) { + return observer.onError(this.exception); + } + + function toString () { + return 'OnError(' + this.exception + ')'; + } + + return function (exception) { + var notification = new Notification('E'); + notification.exception = exception; + notification._accept = _accept; + notification._acceptObservable = _acceptObservable; + notification.toString = toString; + return notification; + }; + }()); + + /** + * Creates an object that represents an OnCompleted notification to an observer. + * @returns {Notification} The OnCompleted notification. + */ + var notificationCreateOnCompleted = Notification.createOnCompleted = (function () { + + function _accept (onNext, onError, onCompleted) { + return onCompleted(); + } + + function _acceptObservable(observer) { + return observer.onCompleted(); + } + + function toString () { + return 'OnCompleted()'; + } + + return function () { + var notification = new Notification('C'); + notification._accept = _accept; + notification._acceptObservable = _acceptObservable; + notification.toString = toString; + return notification; + }; + }()); + + var Enumerator = Rx.internals.Enumerator = function (next) { + this._next = next; + }; + + Enumerator.prototype.next = function () { + return this._next(); + }; + + Enumerator.prototype[$iterator$] = function () { return this; } + + var Enumerable = Rx.internals.Enumerable = function (iterator) { + this._iterator = iterator; + }; + + Enumerable.prototype[$iterator$] = function () { + return this._iterator(); + }; + + Enumerable.prototype.concat = function () { + var sources = this; + return new AnonymousObservable(function (observer) { + var e; + try { + e = sources[$iterator$](); + } catch(err) { + observer.onError(); + return; + } + + var isDisposed, + subscription = new SerialDisposable(); + var cancelable = immediateScheduler.scheduleRecursive(function (self) { + var currentItem; + if (isDisposed) { return; } + + try { + currentItem = e.next(); + } catch (ex) { + observer.onError(ex); + return; + } + + if (currentItem.done) { + observer.onCompleted(); + return; + } + + // Check if promise + var currentValue = currentItem.value; + isPromise(currentValue) && (currentValue = observableFromPromise(currentValue)); + + var d = new SingleAssignmentDisposable(); + subscription.setDisposable(d); + d.setDisposable(currentValue.subscribe( + observer.onNext.bind(observer), + observer.onError.bind(observer), + function () { self(); }) + ); + }); + + return new CompositeDisposable(subscription, cancelable, disposableCreate(function () { + isDisposed = true; + })); + }); + }; + + Enumerable.prototype.catchException = function () { + var sources = this; + return new AnonymousObservable(function (observer) { + var e; + try { + e = sources[$iterator$](); + } catch(err) { + observer.onError(); + return; + } + + var isDisposed, + lastException, + subscription = new SerialDisposable(); + var cancelable = immediateScheduler.scheduleRecursive(function (self) { + if (isDisposed) { return; } + + var currentItem; + try { + currentItem = e.next(); + } catch (ex) { + observer.onError(ex); + return; + } + + if (currentItem.done) { + if (lastException) { + observer.onError(lastException); + } else { + observer.onCompleted(); + } + return; + } + + // Check if promise + var currentValue = currentItem.value; + isPromise(currentValue) && (currentValue = observableFromPromise(currentValue)); + + var d = new SingleAssignmentDisposable(); + subscription.setDisposable(d); + d.setDisposable(currentValue.subscribe( + observer.onNext.bind(observer), + function (exn) { + lastException = exn; + self(); + }, + observer.onCompleted.bind(observer))); + }); + return new CompositeDisposable(subscription, cancelable, disposableCreate(function () { + isDisposed = true; + })); + }); + }; + + var enumerableRepeat = Enumerable.repeat = function (value, repeatCount) { + if (repeatCount == null) { repeatCount = -1; } + return new Enumerable(function () { + var left = repeatCount; + return new Enumerator(function () { + if (left === 0) { return doneEnumerator; } + if (left > 0) { left--; } + return { done: false, value: value }; + }); + }); + }; + + var enumerableFor = Enumerable.forEach = function (source, selector, thisArg) { + selector || (selector = identity); + return new Enumerable(function () { + var index = -1; + return new Enumerator( + function () { + return ++index < source.length ? + { done: false, value: selector.call(thisArg, source[index], index, source) } : + doneEnumerator; + }); + }); + }; + + /** + * Supports push-style iteration over an observable sequence. + */ + var Observer = Rx.Observer = function () { }; + + /** + * Creates a notification callback from an observer. + * + * @param observer Observer object. + * @returns The action that forwards its input notification to the underlying observer. + */ + Observer.prototype.toNotifier = function () { + var observer = this; + return function (n) { + return n.accept(observer); + }; + }; + + /** + * Hides the identity of an observer. + + * @returns An observer that hides the identity of the specified observer. + */ + Observer.prototype.asObserver = function () { + return new AnonymousObserver(this.onNext.bind(this), this.onError.bind(this), this.onCompleted.bind(this)); + }; + + /** + * Checks access to the observer for grammar violations. This includes checking for multiple OnError or OnCompleted calls, as well as reentrancy in any of the observer methods. + * If a violation is detected, an Error is thrown from the offending observer method call. + * + * @returns An observer that checks callbacks invocations against the observer grammar and, if the checks pass, forwards those to the specified observer. + */ + Observer.prototype.checked = function () { return new CheckedObserver(this); }; + + /** + * Creates an observer from the specified OnNext, along with optional OnError, and OnCompleted actions. + * + * @static + * @memberOf Observer + * @param {Function} [onNext] Observer's OnNext action implementation. + * @param {Function} [onError] Observer's OnError action implementation. + * @param {Function} [onCompleted] Observer's OnCompleted action implementation. + * @returns {Observer} The observer object implemented using the given actions. + */ + var observerCreate = Observer.create = function (onNext, onError, onCompleted) { + onNext || (onNext = noop); + onError || (onError = defaultError); + onCompleted || (onCompleted = noop); + return new AnonymousObserver(onNext, onError, onCompleted); + }; + + /** + * Creates an observer from a notification callback. + * + * @static + * @memberOf Observer + * @param {Function} handler Action that handles a notification. + * @returns The observer object that invokes the specified handler using a notification corresponding to each message it receives. + */ + Observer.fromNotifier = function (handler) { + return new AnonymousObserver(function (x) { + return handler(notificationCreateOnNext(x)); + }, function (exception) { + return handler(notificationCreateOnError(exception)); + }, function () { + return handler(notificationCreateOnCompleted()); + }); + }; + + /** + * Schedules the invocation of observer methods on the given scheduler. + * @param {Scheduler} scheduler Scheduler to schedule observer messages on. + * @returns {Observer} Observer whose messages are scheduled on the given scheduler. + */ + Observer.notifyOn = function (scheduler) { + return new ObserveOnObserver(scheduler, this); + }; + + /** + * Abstract base class for implementations of the Observer class. + * This base class enforces the grammar of observers where OnError and OnCompleted are terminal messages. + */ + var AbstractObserver = Rx.internals.AbstractObserver = (function (_super) { + inherits(AbstractObserver, _super); + + /** + * Creates a new observer in a non-stopped state. + * + * @constructor + */ + function AbstractObserver() { + this.isStopped = false; + _super.call(this); + } + + /** + * Notifies the observer of a new element in the sequence. + * + * @memberOf AbstractObserver + * @param {Any} value Next element in the sequence. + */ + AbstractObserver.prototype.onNext = function (value) { + if (!this.isStopped) { + this.next(value); + } + }; + + /** + * Notifies the observer that an exception has occurred. + * + * @memberOf AbstractObserver + * @param {Any} error The error that has occurred. + */ + AbstractObserver.prototype.onError = function (error) { + if (!this.isStopped) { + this.isStopped = true; + this.error(error); + } + }; + + /** + * Notifies the observer of the end of the sequence. + */ + AbstractObserver.prototype.onCompleted = function () { + if (!this.isStopped) { + this.isStopped = true; + this.completed(); + } + }; + + /** + * Disposes the observer, causing it to transition to the stopped state. + */ + AbstractObserver.prototype.dispose = function () { + this.isStopped = true; + }; + + AbstractObserver.prototype.fail = function (e) { + if (!this.isStopped) { + this.isStopped = true; + this.error(e); + return true; + } + + return false; + }; + + return AbstractObserver; + }(Observer)); + + /** + * Class to create an Observer instance from delegate-based implementations of the on* methods. + */ + var AnonymousObserver = Rx.AnonymousObserver = (function (_super) { + inherits(AnonymousObserver, _super); + + /** + * Creates an observer from the specified OnNext, OnError, and OnCompleted actions. + * @param {Any} onNext Observer's OnNext action implementation. + * @param {Any} onError Observer's OnError action implementation. + * @param {Any} onCompleted Observer's OnCompleted action implementation. + */ + function AnonymousObserver(onNext, onError, onCompleted) { + _super.call(this); + this._onNext = onNext; + this._onError = onError; + this._onCompleted = onCompleted; + } + + /** + * Calls the onNext action. + * @param {Any} value Next element in the sequence. + */ + AnonymousObserver.prototype.next = function (value) { + this._onNext(value); + }; + + /** + * Calls the onError action. + * @param {Any} error The error that has occurred. + */ + AnonymousObserver.prototype.error = function (exception) { + this._onError(exception); + }; + + /** + * Calls the onCompleted action. + */ + AnonymousObserver.prototype.completed = function () { + this._onCompleted(); + }; + + return AnonymousObserver; + }(AbstractObserver)); + + var CheckedObserver = (function (_super) { + inherits(CheckedObserver, _super); + + function CheckedObserver(observer) { + _super.call(this); + this._observer = observer; + this._state = 0; // 0 - idle, 1 - busy, 2 - done + } + + var CheckedObserverPrototype = CheckedObserver.prototype; + + CheckedObserverPrototype.onNext = function (value) { + this.checkAccess(); + try { + this._observer.onNext(value); + } catch (e) { + throw e; + } finally { + this._state = 0; + } + }; + + CheckedObserverPrototype.onError = function (err) { + this.checkAccess(); + try { + this._observer.onError(err); + } catch (e) { + throw e; + } finally { + this._state = 2; + } + }; + + CheckedObserverPrototype.onCompleted = function () { + this.checkAccess(); + try { + this._observer.onCompleted(); + } catch (e) { + throw e; + } finally { + this._state = 2; + } + }; + + CheckedObserverPrototype.checkAccess = function () { + if (this._state === 1) { throw new Error('Re-entrancy detected'); } + if (this._state === 2) { throw new Error('Observer completed'); } + if (this._state === 0) { this._state = 1; } + }; + + return CheckedObserver; + }(Observer)); + + var ScheduledObserver = Rx.internals.ScheduledObserver = (function (_super) { + inherits(ScheduledObserver, _super); + + function ScheduledObserver(scheduler, observer) { + _super.call(this); + this.scheduler = scheduler; + this.observer = observer; + this.isAcquired = false; + this.hasFaulted = false; + this.queue = []; + this.disposable = new SerialDisposable(); + } + + ScheduledObserver.prototype.next = function (value) { + var self = this; + this.queue.push(function () { + self.observer.onNext(value); + }); + }; + + ScheduledObserver.prototype.error = function (exception) { + var self = this; + this.queue.push(function () { + self.observer.onError(exception); + }); + }; + + ScheduledObserver.prototype.completed = function () { + var self = this; + this.queue.push(function () { + self.observer.onCompleted(); + }); + }; + + ScheduledObserver.prototype.ensureActive = function () { + var isOwner = false, parent = this; + if (!this.hasFaulted && this.queue.length > 0) { + isOwner = !this.isAcquired; + this.isAcquired = true; + } + if (isOwner) { + this.disposable.setDisposable(this.scheduler.scheduleRecursive(function (self) { + var work; + if (parent.queue.length > 0) { + work = parent.queue.shift(); + } else { + parent.isAcquired = false; + return; + } + try { + work(); + } catch (ex) { + parent.queue = []; + parent.hasFaulted = true; + throw ex; + } + self(); + })); + } + }; + + ScheduledObserver.prototype.dispose = function () { + _super.prototype.dispose.call(this); + this.disposable.dispose(); + }; + + return ScheduledObserver; + }(AbstractObserver)); + + /** @private */ + var ObserveOnObserver = (function (_super) { + inherits(ObserveOnObserver, _super); + + /** @private */ + function ObserveOnObserver() { + _super.apply(this, arguments); + } + + /** @private */ + ObserveOnObserver.prototype.next = function (value) { + _super.prototype.next.call(this, value); + this.ensureActive(); + }; + + /** @private */ + ObserveOnObserver.prototype.error = function (e) { + _super.prototype.error.call(this, e); + this.ensureActive(); + }; + + /** @private */ + ObserveOnObserver.prototype.completed = function () { + _super.prototype.completed.call(this); + this.ensureActive(); + }; + + return ObserveOnObserver; + })(ScheduledObserver); + + var observableProto; + + /** + * Represents a push-style collection. + */ + var Observable = Rx.Observable = (function () { + + function Observable(subscribe) { + this._subscribe = subscribe; + } + + observableProto = Observable.prototype; + + /** + * Subscribes an observer to the observable sequence. + * + * @example + * 1 - source.subscribe(); + * 2 - source.subscribe(observer); + * 3 - source.subscribe(function (x) { console.log(x); }); + * 4 - source.subscribe(function (x) { console.log(x); }, function (err) { console.log(err); }); + * 5 - source.subscribe(function (x) { console.log(x); }, function (err) { console.log(err); }, function () { console.log('done'); }); + * @param {Mixed} [observerOrOnNext] The object that is to receive notifications or an action to invoke for each element in the observable sequence. + * @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence. + * @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence. + * @returns {Diposable} The source sequence whose subscriptions and unsubscriptions happen on the specified scheduler. + */ + observableProto.subscribe = observableProto.forEach = function (observerOrOnNext, onError, onCompleted) { + var subscriber = typeof observerOrOnNext === 'object' ? + observerOrOnNext : + observerCreate(observerOrOnNext, onError, onCompleted); + + return this._subscribe(subscriber); + }; + + return Observable; + })(); + + /** + * Wraps the source sequence in order to run its observer callbacks on the specified scheduler. + * + * This only invokes observer callbacks on a scheduler. In case the subscription and/or unsubscription actions have side-effects + * that require to be run on a scheduler, use subscribeOn. + * + * @param {Scheduler} scheduler Scheduler to notify observers on. + * @returns {Observable} The source sequence whose observations happen on the specified scheduler. + */ + observableProto.observeOn = function (scheduler) { + var source = this; + return new AnonymousObservable(function (observer) { + return source.subscribe(new ObserveOnObserver(scheduler, observer)); + }); + }; + + /** + * Wraps the source sequence in order to run its subscription and unsubscription logic on the specified scheduler. This operation is not commonly used; + * see the remarks section for more information on the distinction between subscribeOn and observeOn. + + * This only performs the side-effects of subscription and unsubscription on the specified scheduler. In order to invoke observer + * callbacks on a scheduler, use observeOn. + + * @param {Scheduler} scheduler Scheduler to perform subscription and unsubscription actions on. + * @returns {Observable} The source sequence whose subscriptions and unsubscriptions happen on the specified scheduler. + */ + observableProto.subscribeOn = function (scheduler) { + var source = this; + return new AnonymousObservable(function (observer) { + var m = new SingleAssignmentDisposable(), d = new SerialDisposable(); + d.setDisposable(m); + m.setDisposable(scheduler.schedule(function () { + d.setDisposable(new ScheduledDisposable(scheduler, source.subscribe(observer))); + })); + return d; + }); + }; + + /** + * Converts a Promise to an Observable sequence + * @param {Promise} An ES6 Compliant promise. + * @returns {Observable} An Observable sequence which wraps the existing promise success and failure. + */ + var observableFromPromise = Observable.fromPromise = function (promise) { + return new AnonymousObservable(function (observer) { + promise.then( + function (value) { + observer.onNext(value); + observer.onCompleted(); + }, + function (reason) { + observer.onError(reason); + }); + + return function () { + if (promise && promise.abort) { + promise.abort(); + } + } + }); + }; + /* + * Converts an existing observable sequence to an ES6 Compatible Promise + * @example + * var promise = Rx.Observable.return(42).toPromise(RSVP.Promise); + * + * // With config + * Rx.config.Promise = RSVP.Promise; + * var promise = Rx.Observable.return(42).toPromise(); + * @param {Function} [promiseCtor] The constructor of the promise. If not provided, it looks for it in Rx.config.Promise. + * @returns {Promise} An ES6 compatible promise with the last value from the observable sequence. + */ + observableProto.toPromise = function (promiseCtor) { + promiseCtor || (promiseCtor = Rx.config.Promise); + if (!promiseCtor) { + throw new Error('Promise type not provided nor in Rx.config.Promise'); + } + var source = this; + return new promiseCtor(function (resolve, reject) { + // No cancellation can be done + var value, hasValue = false; + source.subscribe(function (v) { + value = v; + hasValue = true; + }, function (err) { + reject(err); + }, function () { + if (hasValue) { + resolve(value); + } + }); + }); + }; + /** + * Creates a list from an observable sequence. + * @returns An observable sequence containing a single element with a list containing all the elements of the source sequence. + */ + observableProto.toArray = function () { + var self = this; + return new AnonymousObservable(function(observer) { + var arr = []; + return self.subscribe( + arr.push.bind(arr), + observer.onError.bind(observer), + function () { + observer.onNext(arr); + observer.onCompleted(); + }); + }); + }; + + /** + * Creates an observable sequence from a specified subscribe method implementation. + * + * @example + * var res = Rx.Observable.create(function (observer) { return function () { } ); + * var res = Rx.Observable.create(function (observer) { return Rx.Disposable.empty; } ); + * var res = Rx.Observable.create(function (observer) { } ); + * + * @param {Function} subscribe Implementation of the resulting observable sequence's subscribe method, returning a function that will be wrapped in a Disposable. + * @returns {Observable} The observable sequence with the specified implementation for the Subscribe method. + */ + Observable.create = Observable.createWithDisposable = function (subscribe) { + return new AnonymousObservable(subscribe); + }; + + /** + * Returns an observable sequence that invokes the specified factory function whenever a new observer subscribes. + * + * @example + * var res = Rx.Observable.defer(function () { return Rx.Observable.fromArray([1,2,3]); }); + * @param {Function} observableFactory Observable factory function to invoke for each observer that subscribes to the resulting sequence or Promise. + * @returns {Observable} An observable sequence whose observers trigger an invocation of the given observable factory function. + */ + var observableDefer = Observable.defer = function (observableFactory) { + return new AnonymousObservable(function (observer) { + var result; + try { + result = observableFactory(); + } catch (e) { + return observableThrow(e).subscribe(observer); + } + isPromise(result) && (result = observableFromPromise(result)); + return result.subscribe(observer); + }); + }; + + /** + * Returns an empty observable sequence, using the specified scheduler to send out the single OnCompleted message. + * + * @example + * var res = Rx.Observable.empty(); + * var res = Rx.Observable.empty(Rx.Scheduler.timeout); + * @param {Scheduler} [scheduler] Scheduler to send the termination call on. + * @returns {Observable} An observable sequence with no elements. + */ + var observableEmpty = Observable.empty = function (scheduler) { + scheduler || (scheduler = immediateScheduler); + return new AnonymousObservable(function (observer) { + return scheduler.schedule(function () { + observer.onCompleted(); + }); + }); + }; + + /** + * Converts an array to an observable sequence, using an optional scheduler to enumerate the array. + * + * @example + * var res = Rx.Observable.fromArray([1,2,3]); + * var res = Rx.Observable.fromArray([1,2,3], Rx.Scheduler.timeout); + * @param {Scheduler} [scheduler] Scheduler to run the enumeration of the input sequence on. + * @returns {Observable} The observable sequence whose elements are pulled from the given enumerable sequence. + */ + var observableFromArray = Observable.fromArray = function (array, scheduler) { + scheduler || (scheduler = currentThreadScheduler); + return new AnonymousObservable(function (observer) { + var count = 0, len = array.length; + return scheduler.scheduleRecursive(function (self) { + if (count < len) { + observer.onNext(array[count++]); + self(); + } else { + observer.onCompleted(); + } + }); + }); + }; + + /** + * Converts an iterable into an Observable sequence + * + * @example + * var res = Rx.Observable.fromIterable(new Map()); + * var res = Rx.Observable.fromIterable(new Set(), Rx.Scheduler.timeout); + * @param {Scheduler} [scheduler] Scheduler to run the enumeration of the input sequence on. + * @returns {Observable} The observable sequence whose elements are pulled from the given generator sequence. + */ + Observable.fromIterable = function (iterable, scheduler) { + scheduler || (scheduler = currentThreadScheduler); + return new AnonymousObservable(function (observer) { + var iterator; + try { + iterator = iterable[$iterator$](); + } catch (e) { + observer.onError(e); + return; + } + + return scheduler.scheduleRecursive(function (self) { + var next; + try { + next = iterator.next(); + } catch (err) { + observer.onError(err); + return; + } + + if (next.done) { + observer.onCompleted(); + } else { + observer.onNext(next.value); + self(); + } + }); + }); + }; + + /** + * 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) { + scheduler || (scheduler = currentThreadScheduler); + return new AnonymousObservable(function (observer) { + var first = true, state = initialState; + return scheduler.scheduleRecursive(function (self) { + var hasResult, result; + try { + if (first) { + first = false; + } else { + state = iterate(state); + } + hasResult = condition(state); + if (hasResult) { + result = resultSelector(state); + } + } catch (exception) { + observer.onError(exception); + return; + } + if (hasResult) { + observer.onNext(result); + self(); + } else { + observer.onCompleted(); + } + }); + }); + }; + + /** + * Returns a non-terminating observable sequence, which can be used to denote an infinite duration (e.g. when using reactive joins). + * @returns {Observable} An observable sequence whose observers will never get called. + */ + var observableNever = Observable.never = function () { + return new AnonymousObservable(function () { + return disposableEmpty; + }); + }; + + /** + * This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments. + * @example + * var res = Rx.Observable.of(1,2,3); + * @returns {Observable} The observable sequence whose elements are pulled from the given arguments. + */ + Observable.of = function () { + var len = arguments.length, args = new Array(len); + for(var i = 0; i < len; i++) { args[i] = arguments[i]; } + return observableFromArray(args); + }; + + /** + * This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments. + * @example + * var res = Rx.Observable.of(1,2,3); + * @param {Scheduler} scheduler A scheduler to use for scheduling the arguments. + * @returns {Observable} The observable sequence whose elements are pulled from the given arguments. + */ + var observableOf = Observable.ofWithScheduler = function (scheduler) { + var len = arguments.length - 1, args = new Array(len); + for(var i = 0; i < len; i++) { args[i] = arguments[i + 1]; } + return observableFromArray(args, scheduler); + }; + + /** + * Generates an observable sequence of integral numbers within a specified range, using the specified scheduler to send out observer messages. + * + * @example + * var res = Rx.Observable.range(0, 10); + * var res = Rx.Observable.range(0, 10, Rx.Scheduler.timeout); + * @param {Number} start The value of the first integer in the sequence. + * @param {Number} count The number of sequential integers to generate. + * @param {Scheduler} [scheduler] Scheduler to run the generator loop on. If not specified, defaults to Scheduler.currentThread. + * @returns {Observable} An observable sequence that contains a range of sequential integral numbers. + */ + Observable.range = function (start, count, scheduler) { + scheduler || (scheduler = currentThreadScheduler); + return new AnonymousObservable(function (observer) { + return scheduler.scheduleRecursiveWithState(0, function (i, self) { + if (i < count) { + observer.onNext(start + i); + self(i + 1); + } else { + observer.onCompleted(); + } + }); + }); + }; + + /** + * Generates an observable sequence that repeats the given element the specified number of times, using the specified scheduler to send out observer messages. + * + * @example + * var res = Rx.Observable.repeat(42); + * var res = Rx.Observable.repeat(42, 4); + * 3 - res = Rx.Observable.repeat(42, 4, Rx.Scheduler.timeout); + * 4 - res = Rx.Observable.repeat(42, null, Rx.Scheduler.timeout); + * @param {Mixed} value Element to repeat. + * @param {Number} repeatCount [Optiona] Number of times to repeat the element. If not specified, repeats indefinitely. + * @param {Scheduler} scheduler Scheduler to run the producer loop on. If not specified, defaults to Scheduler.immediate. + * @returns {Observable} An observable sequence that repeats the given element the specified number of times. + */ + Observable.repeat = function (value, repeatCount, scheduler) { + scheduler || (scheduler = currentThreadScheduler); + if (repeatCount == null) { + repeatCount = -1; + } + return observableReturn(value, scheduler).repeat(repeatCount); + }; + + /** + * Returns an observable sequence that contains a single element, using the specified scheduler to send out observer messages. + * There is an alias called 'just', and 'returnValue' for browsers 0) { + s = q.shift(); + subscribe(s); + } else { + activeCount--; + if (isStopped && activeCount === 0) { + observer.onCompleted(); + } + } + })); + }; + group.add(sources.subscribe(function (innerSource) { + if (activeCount < maxConcurrentOrOther) { + activeCount++; + subscribe(innerSource); + } else { + q.push(innerSource); + } + }, observer.onError.bind(observer), function () { + isStopped = true; + if (activeCount === 0) { + observer.onCompleted(); + } + })); + return group; + }); + }; + + /** + * Merges all the observable sequences into a single observable sequence. + * The scheduler is optional and if not specified, the immediate scheduler is used. + * + * @example + * 1 - merged = Rx.Observable.merge(xs, ys, zs); + * 2 - merged = Rx.Observable.merge([xs, ys, zs]); + * 3 - merged = Rx.Observable.merge(scheduler, xs, ys, zs); + * 4 - merged = Rx.Observable.merge(scheduler, [xs, ys, zs]); + * @returns {Observable} The observable sequence that merges the elements of the observable sequences. + */ + var observableMerge = Observable.merge = function () { + var scheduler, sources; + if (!arguments[0]) { + scheduler = immediateScheduler; + sources = slice.call(arguments, 1); + } else if (arguments[0].now) { + scheduler = arguments[0]; + sources = slice.call(arguments, 1); + } else { + scheduler = immediateScheduler; + sources = slice.call(arguments, 0); + } + if (Array.isArray(sources[0])) { + sources = sources[0]; + } + return observableFromArray(sources, scheduler).mergeObservable(); + }; + + /** + * Merges an observable sequence of observable sequences into an observable sequence. + * @returns {Observable} The observable sequence that merges the elements of the inner sequences. + */ + observableProto.mergeObservable = observableProto.mergeAll =function () { + var sources = this; + return new AnonymousObservable(function (observer) { + var group = new CompositeDisposable(), + isStopped = false, + m = new SingleAssignmentDisposable(); + + group.add(m); + m.setDisposable(sources.subscribe(function (innerSource) { + var innerSubscription = new SingleAssignmentDisposable(); + group.add(innerSubscription); + + // Check if Promise or Observable + if (isPromise(innerSource)) { + innerSource = observableFromPromise(innerSource); + } + + innerSubscription.setDisposable(innerSource.subscribe(function (x) { + observer.onNext(x); + }, observer.onError.bind(observer), function () { + group.remove(innerSubscription); + if (isStopped && group.length === 1) { observer.onCompleted(); } + })); + }, observer.onError.bind(observer), function () { + isStopped = true; + if (group.length === 1) { observer.onCompleted(); } + })); + return group; + }); + }; + + /** + * Continues an observable sequence that is terminated normally or by an exception with the next observable sequence. + * @param {Observable} second Second observable sequence used to produce results after the first sequence terminates. + * @returns {Observable} An observable sequence that concatenates the first and second sequence, even if the first sequence terminates exceptionally. + */ + observableProto.onErrorResumeNext = function (second) { + if (!second) { + throw new Error('Second observable is required'); + } + return onErrorResumeNext([this, second]); + }; + + /** + * Continues an observable sequence that is terminated normally or by an exception with the next observable sequence. + * + * @example + * 1 - res = Rx.Observable.onErrorResumeNext(xs, ys, zs); + * 1 - res = Rx.Observable.onErrorResumeNext([xs, ys, zs]); + * @returns {Observable} An observable sequence that concatenates the source sequences, even if a sequence terminates exceptionally. + */ + var onErrorResumeNext = Observable.onErrorResumeNext = function () { + var sources = argsOrArray(arguments, 0); + return new AnonymousObservable(function (observer) { + var pos = 0, subscription = new SerialDisposable(), + cancelable = immediateScheduler.scheduleRecursive(function (self) { + var current, d; + if (pos < sources.length) { + current = sources[pos++]; + isPromise(current) && (current = observableFromPromise(current)); + d = new SingleAssignmentDisposable(); + subscription.setDisposable(d); + d.setDisposable(current.subscribe(observer.onNext.bind(observer), function () { + self(); + }, function () { + self(); + })); + } else { + observer.onCompleted(); + } + }); + return new CompositeDisposable(subscription, cancelable); + }); + }; + + /** + * Returns the values from the source observable sequence only after the other observable sequence produces a value. + * @param {Observable | Promise} other The observable sequence or Promise that triggers propagation of elements of the source sequence. + * @returns {Observable} An observable sequence containing the elements of the source sequence starting from the point the other sequence triggered propagation. + */ + observableProto.skipUntil = function (other) { + var source = this; + return new AnonymousObservable(function (observer) { + var isOpen = false; + var disposables = new CompositeDisposable(source.subscribe(function (left) { + isOpen && observer.onNext(left); + }, observer.onError.bind(observer), function () { + isOpen && observer.onCompleted(); + })); + + isPromise(other) && (other = observableFromPromise(other)); + + var rightSubscription = new SingleAssignmentDisposable(); + disposables.add(rightSubscription); + rightSubscription.setDisposable(other.subscribe(function () { + isOpen = true; + rightSubscription.dispose(); + }, observer.onError.bind(observer), function () { + rightSubscription.dispose(); + })); + + return disposables; + }); + }; + + /** + * Transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence. + * @returns {Observable} The observable sequence that at any point in time produces the elements of the most recent inner observable sequence that has been received. + */ + observableProto['switch'] = observableProto.switchLatest = function () { + var sources = this; + return new AnonymousObservable(function (observer) { + var hasLatest = false, + innerSubscription = new SerialDisposable(), + isStopped = false, + latest = 0, + subscription = sources.subscribe(function (innerSource) { + var d = new SingleAssignmentDisposable(), id = ++latest; + hasLatest = true; + innerSubscription.setDisposable(d); + + // Check if Promise or Observable + if (isPromise(innerSource)) { + innerSource = observableFromPromise(innerSource); + } + + d.setDisposable(innerSource.subscribe(function (x) { + if (latest === id) { + observer.onNext(x); + } + }, function (e) { + if (latest === id) { + observer.onError(e); + } + }, function () { + if (latest === id) { + hasLatest = false; + if (isStopped) { + observer.onCompleted(); + } + } + })); + }, observer.onError.bind(observer), function () { + isStopped = true; + if (!hasLatest) { + observer.onCompleted(); + } + }); + return new CompositeDisposable(subscription, innerSubscription); + }); + }; + + /** + * Returns the values from the source observable sequence until the other observable sequence produces a value. + * @param {Observable | Promise} other Observable sequence or Promise that terminates propagation of elements of the source sequence. + * @returns {Observable} An observable sequence containing the elements of the source sequence up to the point the other sequence interrupted further propagation. + */ + observableProto.takeUntil = function (other) { + var source = this; + return new AnonymousObservable(function (observer) { + isPromise(other) && (other = observableFromPromise(other)); + return new CompositeDisposable( + source.subscribe(observer), + other.subscribe(observer.onCompleted.bind(observer), observer.onError.bind(observer), noop) + ); + }); + }; + + function zipArray(second, resultSelector) { + var first = this; + return new AnonymousObservable(function (observer) { + var index = 0, len = second.length; + return first.subscribe(function (left) { + if (index < len) { + var right = second[index++], result; + try { + result = resultSelector(left, right); + } catch (e) { + observer.onError(e); + return; + } + observer.onNext(result); + } else { + observer.onCompleted(); + } + }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); + }); + } + + /** + * Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences or an array have produced an element at a corresponding index. + * The last element in the arguments must be a function to invoke for each series of elements at corresponding indexes in the sources. + * + * @example + * 1 - res = obs1.zip(obs2, fn); + * 1 - res = x1.zip([1,2,3], fn); + * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + observableProto.zip = function () { + if (Array.isArray(arguments[0])) { + return zipArray.apply(this, arguments); + } + var parent = this, sources = slice.call(arguments), resultSelector = sources.pop(); + sources.unshift(parent); + return new AnonymousObservable(function (observer) { + var n = sources.length, + queues = arrayInitialize(n, function () { return []; }), + isDone = arrayInitialize(n, function () { return false; }); + + function next(i) { + var res, queuedValues; + if (queues.every(function (x) { return x.length > 0; })) { + try { + queuedValues = queues.map(function (x) { return x.shift(); }); + res = resultSelector.apply(parent, queuedValues); + } catch (ex) { + observer.onError(ex); + return; + } + observer.onNext(res); + } else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) { + observer.onCompleted(); + } + }; + + function done(i) { + isDone[i] = true; + if (isDone.every(function (x) { return x; })) { + observer.onCompleted(); + } + } + + var subscriptions = new Array(n); + for (var idx = 0; idx < n; idx++) { + (function (i) { + var source = sources[i], sad = new SingleAssignmentDisposable(); + isPromise(source) && (source = observableFromPromise(source)); + sad.setDisposable(source.subscribe(function (x) { + queues[i].push(x); + next(i); + }, observer.onError.bind(observer), function () { + done(i); + })); + subscriptions[i] = sad; + })(idx); + } + + return new CompositeDisposable(subscriptions); + }); + }; + /** + * Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index. + * @param arguments Observable sources. + * @param {Function} resultSelector Function to invoke for each series of elements at corresponding indexes in the sources. + * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + Observable.zip = function () { + var args = slice.call(arguments, 0), + first = args.shift(); + return first.zip.apply(first, args); + }; + + /** + * Merges the specified observable sequences into one observable sequence by emitting a list with the elements of the observable sequences at corresponding indexes. + * @param arguments Observable sources. + * @returns {Observable} An observable sequence containing lists of elements at corresponding indexes. + */ + Observable.zipArray = function () { + var sources = argsOrArray(arguments, 0); + return new AnonymousObservable(function (observer) { + var n = sources.length, + queues = arrayInitialize(n, function () { return []; }), + isDone = arrayInitialize(n, function () { return false; }); + + function next(i) { + if (queues.every(function (x) { return x.length > 0; })) { + var res = queues.map(function (x) { return x.shift(); }); + observer.onNext(res); + } else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) { + observer.onCompleted(); + return; + } + }; + + function done(i) { + isDone[i] = true; + if (isDone.every(identity)) { + observer.onCompleted(); + return; + } + } + + var subscriptions = new Array(n); + for (var idx = 0; idx < n; idx++) { + (function (i) { + subscriptions[i] = new SingleAssignmentDisposable(); + subscriptions[i].setDisposable(sources[i].subscribe(function (x) { + queues[i].push(x); + next(i); + }, observer.onError.bind(observer), function () { + done(i); + })); + })(idx); + } + + var compositeDisposable = new CompositeDisposable(subscriptions); + compositeDisposable.add(disposableCreate(function () { + for (var qIdx = 0, qLen = queues.length; qIdx < qLen; qIdx++) { + queues[qIdx] = []; + } + })); + return compositeDisposable; + }); + }; + + /** + * Hides the identity of an observable sequence. + * @returns {Observable} An observable sequence that hides the identity of the source sequence. + */ + observableProto.asObservable = function () { + var source = this; + return new AnonymousObservable(function (observer) { + return source.subscribe(observer); + }); + }; + + /** + * Projects each element of an observable sequence into zero or more buffers which are produced based on element count information. + * + * @example + * var res = xs.bufferWithCount(10); + * var res = xs.bufferWithCount(10, 1); + * @param {Number} count Length of each buffer. + * @param {Number} [skip] Number of elements to skip between creation of consecutive buffers. If not provided, defaults to the count. + * @returns {Observable} An observable sequence of buffers. + */ + observableProto.bufferWithCount = function (count, skip) { + if (typeof skip !== 'number') { + skip = count; + } + return this.windowWithCount(count, skip).selectMany(function (x) { + return x.toArray(); + }).where(function (x) { + return x.length > 0; + }); + }; + + /** + * Dematerializes the explicit notification values of an observable sequence as implicit notifications. + * @returns {Observable} An observable sequence exhibiting the behavior corresponding to the source sequence's notification values. + */ + observableProto.dematerialize = function () { + var source = this; + return new AnonymousObservable(function (observer) { + return source.subscribe(function (x) { + return x.accept(observer); + }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); + }); + }; + + /** + * Returns an observable sequence that contains only distinct contiguous elements according to the keySelector and the comparer. + * + * var obs = observable.distinctUntilChanged(); + * var obs = observable.distinctUntilChanged(function (x) { return x.id; }); + * var obs = observable.distinctUntilChanged(function (x) { return x.id; }, function (x, y) { return x === y; }); + * + * @param {Function} [keySelector] A function to compute the comparison key for each element. If not provided, it projects the value. + * @param {Function} [comparer] Equality comparer for computed key values. If not provided, defaults to an equality comparer function. + * @returns {Observable} An observable sequence only containing the distinct contiguous elements, based on a computed key value, from the source sequence. + */ + observableProto.distinctUntilChanged = function (keySelector, comparer) { + var source = this; + keySelector || (keySelector = identity); + comparer || (comparer = defaultComparer); + return new AnonymousObservable(function (observer) { + var hasCurrentKey = false, currentKey; + return source.subscribe(function (value) { + var comparerEquals = false, key; + try { + key = keySelector(value); + } catch (exception) { + observer.onError(exception); + return; + } + if (hasCurrentKey) { + try { + comparerEquals = comparer(currentKey, key); + } catch (exception) { + observer.onError(exception); + return; + } + } + if (!hasCurrentKey || !comparerEquals) { + hasCurrentKey = true; + currentKey = key; + observer.onNext(value); + } + }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); + }); + }; + + /** + * Invokes an action for each element in the observable sequence and invokes an action upon graceful or exceptional termination of the observable sequence. + * This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline. + * + * @example + * var res = observable.doAction(observer); + * var res = observable.doAction(onNext); + * var res = observable.doAction(onNext, onError); + * var res = observable.doAction(onNext, onError, onCompleted); + * @param {Mixed} observerOrOnNext Action to invoke for each element in the observable sequence or an observer. + * @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function. + * @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function. + * @returns {Observable} The source sequence with the side-effecting behavior applied. + */ + observableProto['do'] = observableProto.doAction = function (observerOrOnNext, onError, onCompleted) { + var source = this, onNextFunc; + if (typeof observerOrOnNext === 'function') { + onNextFunc = observerOrOnNext; + } else { + onNextFunc = observerOrOnNext.onNext.bind(observerOrOnNext); + onError = observerOrOnNext.onError.bind(observerOrOnNext); + onCompleted = observerOrOnNext.onCompleted.bind(observerOrOnNext); + } + return new AnonymousObservable(function (observer) { + return source.subscribe(function (x) { + try { + onNextFunc(x); + } catch (e) { + observer.onError(e); + } + observer.onNext(x); + }, function (exception) { + if (!onError) { + observer.onError(exception); + } else { + try { + onError(exception); + } catch (e) { + observer.onError(e); + } + observer.onError(exception); + } + }, function () { + if (!onCompleted) { + observer.onCompleted(); + } else { + try { + onCompleted(); + } catch (e) { + observer.onError(e); + } + observer.onCompleted(); + } + }); + }); + }; + + /** + * Invokes a specified action after the source observable sequence terminates gracefully or exceptionally. + * + * @example + * var res = observable.finallyAction(function () { console.log('sequence ended'; }); + * @param {Function} finallyAction Action to invoke after the source observable sequence terminates. + * @returns {Observable} Source sequence with the action-invoking termination behavior applied. + */ + observableProto['finally'] = observableProto.finallyAction = function (action) { + var source = this; + return new AnonymousObservable(function (observer) { + var subscription; + try { + subscription = source.subscribe(observer); + } catch (e) { + action(); + throw e; + } + return disposableCreate(function () { + try { + subscription.dispose(); + } catch (e) { + throw e; + } finally { + action(); + } + }); + }); + }; + + /** + * Ignores all elements in an observable sequence leaving only the termination messages. + * @returns {Observable} An empty observable sequence that signals termination, successful or exceptional, of the source sequence. + */ + observableProto.ignoreElements = function () { + var source = this; + return new AnonymousObservable(function (observer) { + return source.subscribe(noop, observer.onError.bind(observer), observer.onCompleted.bind(observer)); + }); + }; + + /** + * Materializes the implicit notifications of an observable sequence as explicit notification values. + * @returns {Observable} An observable sequence containing the materialized notification values from the source sequence. + */ + observableProto.materialize = function () { + var source = this; + return new AnonymousObservable(function (observer) { + return source.subscribe(function (value) { + observer.onNext(notificationCreateOnNext(value)); + }, function (e) { + observer.onNext(notificationCreateOnError(e)); + observer.onCompleted(); + }, function () { + observer.onNext(notificationCreateOnCompleted()); + observer.onCompleted(); + }); + }); + }; + + /** + * Repeats the observable sequence a specified number of times. If the repeat count is not specified, the sequence repeats indefinitely. + * + * @example + * var res = repeated = source.repeat(); + * var res = repeated = source.repeat(42); + * @param {Number} [repeatCount] Number of times to repeat the sequence. If not provided, repeats the sequence indefinitely. + * @returns {Observable} The observable sequence producing the elements of the given sequence repeatedly. + */ + observableProto.repeat = function (repeatCount) { + return enumerableRepeat(this, repeatCount).concat(); + }; + + /** + * Repeats the source observable sequence the specified number of times or until it successfully terminates. If the retry count is not specified, it retries indefinitely. + * + * @example + * var res = retried = retry.repeat(); + * var res = retried = retry.repeat(42); + * @param {Number} [retryCount] Number of times to retry the sequence. If not provided, retry the sequence indefinitely. + * @returns {Observable} An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully. + */ + observableProto.retry = function (retryCount) { + return enumerableRepeat(this, retryCount).catchException(); + }; + + /** + * Applies an accumulator function over an observable sequence and returns each intermediate result. The optional seed value is used as the initial accumulator value. + * For aggregation behavior with no intermediate results, see Observable.aggregate. + * @example + * var res = source.scan(function (acc, x) { return acc + x; }); + * var res = source.scan(0, function (acc, x) { return acc + x; }); + * @param {Mixed} [seed] The initial accumulator value. + * @param {Function} accumulator An accumulator function to be invoked on each element. + * @returns {Observable} An observable sequence containing the accumulated values. + */ + observableProto.scan = function () { + var hasSeed = false, seed, accumulator, source = this; + if (arguments.length === 2) { + hasSeed = true; + seed = arguments[0]; + accumulator = arguments[1]; + } else { + accumulator = arguments[0]; + } + return new AnonymousObservable(function (observer) { + var hasAccumulation, accumulation, hasValue; + return source.subscribe ( + function (x) { + try { + if (!hasValue) { + hasValue = true; + } + + if (hasAccumulation) { + accumulation = accumulator(accumulation, x); + } else { + accumulation = hasSeed ? accumulator(seed, x) : x; + hasAccumulation = true; + } + } catch (e) { + observer.onError(e); + return; + } + + observer.onNext(accumulation); + }, + observer.onError.bind(observer), + function () { + if (!hasValue && hasSeed) { + observer.onNext(seed); + } + observer.onCompleted(); + } + ); + }); + }; + + /** + * Bypasses a specified number of elements at the end of an observable sequence. + * @description + * This operator accumulates a queue with a length enough to store the first `count` elements. As more elements are + * received, elements are taken from the front of the queue and produced on the result sequence. This causes elements to be delayed. + * @param count Number of elements to bypass at the end of the source sequence. + * @returns {Observable} An observable sequence containing the source sequence elements except for the bypassed ones at the end. + */ + observableProto.skipLast = function (count) { + var source = this; + return new AnonymousObservable(function (observer) { + var q = []; + return source.subscribe(function (x) { + q.push(x); + if (q.length > count) { + observer.onNext(q.shift()); + } + }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); + }); + }; + + /** + * Prepends a sequence of values to an observable sequence with an optional scheduler and an argument list of values to prepend. + * + * var res = source.startWith(1, 2, 3); + * var res = source.startWith(Rx.Scheduler.timeout, 1, 2, 3); + * + * @memberOf Observable# + * @returns {Observable} The source sequence prepended with the specified values. + */ + observableProto.startWith = function () { + var values, scheduler, start = 0; + if (!!arguments.length && 'now' in Object(arguments[0])) { + scheduler = arguments[0]; + start = 1; + } else { + scheduler = immediateScheduler; + } + values = slice.call(arguments, start); + return enumerableFor([observableFromArray(values, scheduler), this]).concat(); + }; + + /** + * Returns a specified number of contiguous elements from the end of an observable sequence, using an optional scheduler to drain the queue. + * + * @example + * var res = source.takeLast(5); + * var res = source.takeLast(5, Rx.Scheduler.timeout); + * + * @description + * This operator accumulates a buffer with a length enough to store elements count elements. Upon completion of + * the source sequence, this buffer is drained on the result sequence. This causes the elements to be delayed. + * @param {Number} count Number of elements to take from the end of the source sequence. + * @param {Scheduler} [scheduler] Scheduler used to drain the queue upon completion of the source sequence. + * @returns {Observable} An observable sequence containing the specified number of elements from the end of the source sequence. + */ + observableProto.takeLast = function (count, scheduler) { + return this.takeLastBuffer(count).selectMany(function (xs) { return observableFromArray(xs, scheduler); }); + }; + + /** + * Returns an array with the specified number of contiguous elements from the end of an observable sequence. + * + * @description + * This operator accumulates a buffer with a length enough to store count elements. Upon completion of the + * source sequence, this buffer is produced on the result sequence. + * @param {Number} count Number of elements to take from the end of the source sequence. + * @returns {Observable} An observable sequence containing a single array with the specified number of elements from the end of the source sequence. + */ + observableProto.takeLastBuffer = function (count) { + var source = this; + return new AnonymousObservable(function (observer) { + var q = []; + return source.subscribe(function (x) { + q.push(x); + if (q.length > count) { + q.shift(); + } + }, observer.onError.bind(observer), function () { + observer.onNext(q); + observer.onCompleted(); + }); + }); + }; + + /** + * Projects each element of an observable sequence into zero or more windows which are produced based on element count information. + * + * var res = xs.windowWithCount(10); + * var res = xs.windowWithCount(10, 1); + * @param {Number} count Length of each window. + * @param {Number} [skip] Number of elements to skip between creation of consecutive windows. If not specified, defaults to the count. + * @returns {Observable} An observable sequence of windows. + */ + observableProto.windowWithCount = function (count, skip) { + var source = this; + if (count <= 0) { + throw new Error(argumentOutOfRange); + } + if (arguments.length === 1) { + skip = count; + } + if (skip <= 0) { + throw new Error(argumentOutOfRange); + } + return new AnonymousObservable(function (observer) { + var m = new SingleAssignmentDisposable(), + refCountDisposable = new RefCountDisposable(m), + n = 0, + q = [], + createWindow = function () { + var s = new Subject(); + q.push(s); + observer.onNext(addRef(s, refCountDisposable)); + }; + createWindow(); + m.setDisposable(source.subscribe(function (x) { + var s; + for (var i = 0, len = q.length; i < len; i++) { + q[i].onNext(x); + } + var c = n - count + 1; + if (c >= 0 && c % skip === 0) { + s = q.shift(); + s.onCompleted(); + } + n++; + if (n % skip === 0) { + createWindow(); + } + }, function (exception) { + while (q.length > 0) { + q.shift().onError(exception); + } + observer.onError(exception); + }, function () { + while (q.length > 0) { + q.shift().onCompleted(); + } + observer.onCompleted(); + })); + return refCountDisposable; + }); + }; + + function concatMap(selector) { + return this.map(function (x, i) { + var result = selector(x, i); + return isPromise(result) ? observableFromPromise(result) : result; + }).concatAll(); + } + + function concatMapObserver(onNext, onError, onCompleted) { + var source = this; + return new AnonymousObservable(function (observer) { + var index = 0; + + return source.subscribe( + function (x) { + observer.onNext(onNext(x, index++)); + }, + function (err) { + observer.onNext(onError(err)); + observer.completed(); + }, + function () { + observer.onNext(onCompleted()); + observer.onCompleted(); + }); + }).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.selectMany(function (x) { return Rx.Observable.range(0, x); }); + * Or: + * Projects each element of an observable sequence to an observable sequence, invokes the result selector for the source element and each of the corresponding inner sequence's elements, and merges the results into one observable sequence. + * + * var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); }, function (x, y) { return x + y; }); + * Or: + * Projects each element of the source observable sequence to the other observable sequence and merges the resulting observable sequences into one observable sequence. + * + * var res = source.selectMany(Rx.Observable.fromArray([1,2,3])); + * @param selector A transform function to apply to each element or an observable sequence to project each element from the + * source sequence onto which could be either an observable or Promise. + * @param {Function} [resultSelector] A transform function to apply to each element of the intermediate sequence. + * @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) { + if (resultSelector) { + return this.concatMap(function (x, i) { + var selectorResult = selector(x, i), + result = isPromise(selectorResult) ? observableFromPromise(selectorResult) : selectorResult; + + return result.map(function (y) { + return resultSelector(x, y, i); + }); + }); + } + if (typeof selector === 'function') { + return concatMap.call(this, selector); + } + return concatMap.call(this, function () { + return selector; + }); + }; + + /** + * Returns the elements of the specified sequence or the specified value in a singleton sequence if the sequence is empty. + * + * var res = obs = xs.defaultIfEmpty(); + * 2 - obs = xs.defaultIfEmpty(false); + * + * @memberOf Observable# + * @param defaultValue The value to return if the sequence is empty. If not provided, this defaults to null. + * @returns {Observable} An observable sequence that contains the specified default value if the source is empty; otherwise, the elements of the source itself. + */ + observableProto.defaultIfEmpty = function (defaultValue) { + var source = this; + if (defaultValue === undefined) { + defaultValue = null; + } + return new AnonymousObservable(function (observer) { + var found = false; + return source.subscribe(function (x) { + found = true; + observer.onNext(x); + }, observer.onError.bind(observer), function () { + if (!found) { + observer.onNext(defaultValue); + } + observer.onCompleted(); + }); + }); + }; + + /** + * Returns an observable sequence that contains only distinct elements according to the keySelector and the comparer. + * Usage of this operator should be considered carefully due to the maintenance of an internal lookup structure which can grow large. + * + * @example + * var res = obs = xs.distinct(); + * 2 - obs = xs.distinct(function (x) { return x.id; }); + * 2 - obs = xs.distinct(function (x) { return x.id; }, function (x) { return x.toString(); }); + * @param {Function} [keySelector] A function to compute the comparison key for each element. + * @param {Function} [keySerializer] Used to serialize the given object into a string for object comparison. + * @returns {Observable} An observable sequence only containing the distinct elements, based on a computed key value, from the source sequence. + */ + observableProto.distinct = function (keySelector, keySerializer) { + var source = this; + keySelector || (keySelector = identity); + keySerializer || (keySerializer = defaultKeySerializer); + return new AnonymousObservable(function (observer) { + var hashSet = {}; + return source.subscribe(function (x) { + var key, serializedKey, otherKey, hasMatch = false; + try { + key = keySelector(x); + serializedKey = keySerializer(key); + } catch (exception) { + observer.onError(exception); + return; + } + for (otherKey in hashSet) { + if (serializedKey === otherKey) { + hasMatch = true; + break; + } + } + if (!hasMatch) { + hashSet[serializedKey] = null; + observer.onNext(x); + } + }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); + }); + }; + + /** + * Groups the elements of an observable sequence according to a specified key selector function and comparer and selects the resulting elements by using a specified function. + * + * @example + * var res = observable.groupBy(function (x) { return x.id; }); + * 2 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }); + * 3 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }, function (x) { return x.toString(); }); + * @param {Function} keySelector A function to extract the key for each element. + * @param {Function} [elementSelector] A function to map each source element to an element in an observable group. + * @param {Function} [keySerializer] Used to serialize the given object into a string for object comparison. + * @returns {Observable} A sequence of observable groups, each of which corresponds to a unique key value, containing all elements that share that same key value. + */ + observableProto.groupBy = function (keySelector, elementSelector, keySerializer) { + return this.groupByUntil(keySelector, elementSelector, function () { + return observableNever(); + }, keySerializer); + }; + + /** + * Groups the elements of an observable sequence according to a specified key selector function. + * A duration selector function is used to control the lifetime of groups. When a group expires, it receives an OnCompleted notification. When a new element with the same + * key value as a reclaimed group occurs, the group will be reborn with a new lifetime request. + * + * @example + * var res = observable.groupByUntil(function (x) { return x.id; }, null, function () { return Rx.Observable.never(); }); + * 2 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }, function () { return Rx.Observable.never(); }); + * 3 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }, function () { return Rx.Observable.never(); }, function (x) { return x.toString(); }); + * @param {Function} keySelector A function to extract the key for each element. + * @param {Function} durationSelector A function to signal the expiration of a group. + * @param {Function} [keySerializer] Used to serialize the given object into a string for object comparison. + * @returns {Observable} + * A sequence of observable groups, each of which corresponds to a unique key value, containing all elements that share that same key value. + * If a group's lifetime expires, a new group with the same key value can be created once an element with such a key value is encoutered. + * + */ + observableProto.groupByUntil = function (keySelector, elementSelector, durationSelector, keySerializer) { + var source = this; + elementSelector || (elementSelector = identity); + keySerializer || (keySerializer = defaultKeySerializer); + return new AnonymousObservable(function (observer) { + var map = {}, + groupDisposable = new CompositeDisposable(), + refCountDisposable = new RefCountDisposable(groupDisposable); + groupDisposable.add(source.subscribe(function (x) { + var duration, durationGroup, element, fireNewMapEntry, group, key, serializedKey, md, writer, w; + try { + key = keySelector(x); + serializedKey = keySerializer(key); + } catch (e) { + for (w in map) { + map[w].onError(e); + } + observer.onError(e); + return; + } + fireNewMapEntry = false; + try { + writer = map[serializedKey]; + if (!writer) { + writer = new Subject(); + map[serializedKey] = writer; + fireNewMapEntry = true; + } + } catch (e) { + for (w in map) { + map[w].onError(e); + } + observer.onError(e); + return; + } + if (fireNewMapEntry) { + group = new GroupedObservable(key, writer, refCountDisposable); + durationGroup = new GroupedObservable(key, writer); + try { + duration = durationSelector(durationGroup); + } catch (e) { + for (w in map) { + map[w].onError(e); + } + observer.onError(e); + return; + } + observer.onNext(group); + md = new SingleAssignmentDisposable(); + groupDisposable.add(md); + var expire = function () { + if (serializedKey in map) { + delete map[serializedKey]; + writer.onCompleted(); + } + groupDisposable.remove(md); + }; + md.setDisposable(duration.take(1).subscribe(noop, function (exn) { + for (w in map) { + map[w].onError(exn); + } + observer.onError(exn); + }, function () { + expire(); + })); + } + try { + element = elementSelector(x); + } catch (e) { + for (w in map) { + map[w].onError(e); + } + observer.onError(e); + return; + } + writer.onNext(element); + }, function (ex) { + for (var w in map) { + map[w].onError(ex); + } + observer.onError(ex); + }, function () { + for (var w in map) { + map[w].onCompleted(); + } + observer.onCompleted(); + })); + return refCountDisposable; + }); + }; + + /** + * Projects each element of an observable sequence into a new form by incorporating the element's index. + * @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element. + * @param {Any} [thisArg] Object to use as this when executing callback. + * @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source. + */ + observableProto.select = observableProto.map = function (selector, thisArg) { + var parent = this; + return new AnonymousObservable(function (observer) { + var count = 0; + return parent.subscribe(function (value) { + var result; + try { + result = selector.call(thisArg, value, count++, parent); + } catch (exception) { + observer.onError(exception); + return; + } + observer.onNext(result); + }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); + }); + }; + + /** + * Retrieves the value of a specified property from all elements in the Observable sequence. + * @param {String} property The property to pluck. + * @returns {Observable} Returns a new Observable sequence of property values. + */ + observableProto.pluck = function (property) { + return this.select(function (x) { return x[property]; }); + }; + + function selectMany(selector) { + return this.select(function (x, i) { + var result = selector(x, i); + return isPromise(result) ? observableFromPromise(result) : result; + }).mergeObservable(); + } + + function selectManyObserver(onNext, onError, onCompleted) { + var source = this; + return new AnonymousObservable(function (observer) { + var index = 0; + + return source.subscribe( + function (x) { + observer.onNext(onNext(x, index++)); + }, + function (err) { + observer.onNext(onError(err)); + observer.completed(); + }, + function () { + observer.onNext(onCompleted()); + observer.onCompleted(); + }); + }).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 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.selectMany = observableProto.flatMap = function (selector, resultSelector) { + if (resultSelector) { + return this.selectMany(function (x, i) { + var selectorResult = selector(x, i), + result = isPromise(selectorResult) ? observableFromPromise(selectorResult) : selectorResult; + + return result.select(function (y) { + return resultSelector(x, y, i); + }); + }); + } + if (typeof selector === 'function') { + return selectMany.call(this, selector); + } + return selectMany.call(this, function () { + return selector; + }); + }; + + /** + * Projects each element of an observable sequence into a new sequence of observable sequences by incorporating the element's index and then + * transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence. + * @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element. + * @param {Any} [thisArg] Object to use as this when executing callback. + * @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source producing an Observable of Observable sequences + * and that at any point in time produces the elements of the most recent inner observable sequence that has been received. + */ + observableProto.selectSwitch = observableProto.flatMapLatest = observableProto.switchMap = function (selector, thisArg) { + return this.select(selector, thisArg).switchLatest(); + }; + + /** + * Bypasses a specified number of elements in an observable sequence and then returns the remaining elements. + * @param {Number} count The number of elements to skip before returning the remaining elements. + * @returns {Observable} An observable sequence that contains the elements that occur after the specified index in the input sequence. + */ + observableProto.skip = function (count) { + if (count < 0) { + throw new Error(argumentOutOfRange); + } + var observable = this; + return new AnonymousObservable(function (observer) { + var remaining = count; + return observable.subscribe(function (x) { + if (remaining <= 0) { + observer.onNext(x); + } else { + remaining--; + } + }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); + }); + }; + + /** + * Bypasses elements in an observable sequence as long as a specified condition is true and then returns the remaining elements. + * The element's index is used in the logic of the predicate function. + * + * var res = source.skipWhile(function (value) { return value < 10; }); + * var res = source.skipWhile(function (value, index) { return value < 10 || index < 10; }); + * @param {Function} predicate A function to test each element for a condition; the second parameter of the function represents the index of the source element. + * @param {Any} [thisArg] Object to use as this when executing callback. + * @returns {Observable} An observable sequence that contains the elements from the input sequence starting at the first element in the linear series that does not pass the test specified by predicate. + */ + observableProto.skipWhile = function (predicate, thisArg) { + var source = this; + return new AnonymousObservable(function (observer) { + var i = 0, running = false; + return source.subscribe(function (x) { + if (!running) { + try { + running = !predicate.call(thisArg, x, i++, source); + } catch (e) { + observer.onError(e); + return; + } + } + if (running) { + observer.onNext(x); + } + }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); + }); + }; + + /** + * Returns a specified number of contiguous elements from the start of an observable sequence, using the specified scheduler for the edge case of take(0). + * + * var res = source.take(5); + * var res = source.take(0, Rx.Scheduler.timeout); + * @param {Number} count The number of elements to return. + * @param {Scheduler} [scheduler] Scheduler used to produce an OnCompleted message in case -1); + } + }); + } + } + stackA.pop(); + stackB.pop(); + + return result; + } + var slice = Array.prototype.slice; + function argsOrArray(args, idx) { + return args.length === 1 && Array.isArray(args[idx]) ? + args[idx] : + slice.call(args); + } + var hasProp = {}.hasOwnProperty; + + /** @private */ + var inherits = this.inherits = Rx.internals.inherits = function (child, parent) { + function __() { this.constructor = child; } + __.prototype = parent.prototype; + child.prototype = new __(); + }; + + /** @private */ + var addProperties = Rx.internals.addProperties = function (obj) { + var sources = slice.call(arguments, 1); + for (var i = 0, len = sources.length; i < len; i++) { + var source = sources[i]; + for (var prop in source) { + obj[prop] = source[prop]; + } + } + }; + + // Rx Utils + var addRef = Rx.internals.addRef = function (xs, r) { + return new AnonymousObservable(function (observer) { + return new CompositeDisposable(r.getDisposable(), xs.subscribe(observer)); + }); + }; + + // Collection polyfills + function arrayInitialize(count, factory) { + var a = new Array(count); + for (var i = 0; i < count; i++) { + a[i] = factory(); + } + return a; + } + + // Utilities + if (!Function.prototype.bind) { + Function.prototype.bind = function (that) { + var target = this, + args = slice.call(arguments, 1); + var bound = function () { + if (this instanceof bound) { + function F() { } + F.prototype = target.prototype; + var self = new F(); + var result = target.apply(self, args.concat(slice.call(arguments))); + if (Object(result) === result) { + return result; + } + return self; + } else { + return target.apply(that, args.concat(slice.call(arguments))); + } + }; + + return bound; + }; + } + + var boxedString = Object("a"), + splitString = boxedString[0] != "a" || !(0 in boxedString); + if (!Array.prototype.every) { + Array.prototype.every = function every(fun /*, thisp */) { + var object = Object(this), + self = splitString && {}.toString.call(this) == stringClass ? + this.split("") : + object, + length = self.length >>> 0, + thisp = arguments[1]; + + if ({}.toString.call(fun) != funcClass) { + throw new TypeError(fun + " is not a function"); + } + + for (var i = 0; i < length; i++) { + if (i in self && !fun.call(thisp, self[i], i, object)) { + return false; + } + } + return true; + }; + } + + if (!Array.prototype.map) { + Array.prototype.map = function map(fun /*, thisp*/) { + var object = Object(this), + self = splitString && {}.toString.call(this) == stringClass ? + this.split("") : + object, + length = self.length >>> 0, + result = Array(length), + thisp = arguments[1]; + + if ({}.toString.call(fun) != funcClass) { + throw new TypeError(fun + " is not a function"); + } + + for (var i = 0; i < length; i++) { + if (i in self) + result[i] = fun.call(thisp, self[i], i, object); + } + return result; + }; + } + + if (!Array.prototype.filter) { + Array.prototype.filter = function (predicate) { + var results = [], item, t = new Object(this); + for (var i = 0, len = t.length >>> 0; i < len; i++) { + item = t[i]; + if (i in t && predicate.call(arguments[1], item, i, t)) { + results.push(item); + } + } + return results; + }; + } + + if (!Array.isArray) { + Array.isArray = function (arg) { + return Object.prototype.toString.call(arg) == arrayClass; + }; + } + + if (!Array.prototype.indexOf) { + Array.prototype.indexOf = function indexOf(searchElement) { + var t = Object(this); + var len = t.length >>> 0; + if (len === 0) { + return -1; + } + var n = 0; + if (arguments.length > 1) { + n = Number(arguments[1]); + if (n !== n) { + n = 0; + } else if (n !== 0 && n != Infinity && n !== -Infinity) { + n = (n > 0 || -1) * Math.floor(Math.abs(n)); + } + } + if (n >= len) { + return -1; + } + var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0); + for (; k < len; k++) { + if (k in t && t[k] === searchElement) { + return k; + } + } + return -1; + }; + } + + // Collections + var IndexedItem = function (id, value) { + this.id = id; + this.value = value; + }; + + IndexedItem.prototype.compareTo = function (other) { + var c = this.value.compareTo(other.value); + if (c === 0) { + c = this.id - other.id; + } + return c; + }; + + // Priority Queue for Scheduling + var PriorityQueue = Rx.internals.PriorityQueue = function (capacity) { + this.items = new Array(capacity); + this.length = 0; + }; + + var priorityProto = PriorityQueue.prototype; + priorityProto.isHigherPriority = function (left, right) { + return this.items[left].compareTo(this.items[right]) < 0; + }; + + priorityProto.percolate = function (index) { + if (index >= this.length || index < 0) { + return; + } + var parent = index - 1 >> 1; + if (parent < 0 || parent === index) { + return; + } + if (this.isHigherPriority(index, parent)) { + var temp = this.items[index]; + this.items[index] = this.items[parent]; + this.items[parent] = temp; + this.percolate(parent); + } + }; + + priorityProto.heapify = function (index) { + if (index === undefined) { + index = 0; + } + if (index >= this.length || index < 0) { + return; + } + var left = 2 * index + 1, + right = 2 * index + 2, + first = index; + if (left < this.length && this.isHigherPriority(left, first)) { + first = left; + } + if (right < this.length && this.isHigherPriority(right, first)) { + first = right; + } + if (first !== index) { + var temp = this.items[index]; + this.items[index] = this.items[first]; + this.items[first] = temp; + this.heapify(first); + } + }; + + priorityProto.peek = function () { return this.items[0].value; }; + + priorityProto.removeAt = function (index) { + this.items[index] = this.items[--this.length]; + delete this.items[this.length]; + this.heapify(); + }; + + priorityProto.dequeue = function () { + var result = this.peek(); + this.removeAt(0); + return result; + }; + + priorityProto.enqueue = function (item) { + var index = this.length++; + this.items[index] = new IndexedItem(PriorityQueue.count++, item); + this.percolate(index); + }; + + priorityProto.remove = function (item) { + for (var i = 0; i < this.length; i++) { + if (this.items[i].value === item) { + this.removeAt(i); + return true; + } + } + return false; + }; + PriorityQueue.count = 0; + /** + * Represents a group of disposable resources that are disposed together. + * @constructor + */ + var CompositeDisposable = Rx.CompositeDisposable = function () { + this.disposables = argsOrArray(arguments, 0); + this.isDisposed = false; + this.length = this.disposables.length; + }; + + var CompositeDisposablePrototype = CompositeDisposable.prototype; + + /** + * Adds a disposable to the CompositeDisposable or disposes the disposable if the CompositeDisposable is disposed. + * @param {Mixed} item Disposable to add. + */ + CompositeDisposablePrototype.add = function (item) { + if (this.isDisposed) { + item.dispose(); + } else { + this.disposables.push(item); + this.length++; + } + }; + + /** + * Removes and disposes the first occurrence of a disposable from the CompositeDisposable. + * @param {Mixed} item Disposable to remove. + * @returns {Boolean} true if found; false otherwise. + */ + CompositeDisposablePrototype.remove = function (item) { + var shouldDispose = false; + if (!this.isDisposed) { + var idx = this.disposables.indexOf(item); + if (idx !== -1) { + shouldDispose = true; + this.disposables.splice(idx, 1); + this.length--; + item.dispose(); + } + + } + return shouldDispose; + }; + + /** + * Disposes all disposables in the group and removes them from the group. + */ + CompositeDisposablePrototype.dispose = function () { + if (!this.isDisposed) { + this.isDisposed = true; + var currentDisposables = this.disposables.slice(0); + this.disposables = []; + this.length = 0; + + for (var i = 0, len = currentDisposables.length; i < len; i++) { + currentDisposables[i].dispose(); + } + } + }; + + /** + * Removes and disposes all disposables from the CompositeDisposable, but does not dispose the CompositeDisposable. + */ + CompositeDisposablePrototype.clear = function () { + var currentDisposables = this.disposables.slice(0); + this.disposables = []; + this.length = 0; + for (var i = 0, len = currentDisposables.length; i < len; i++) { + currentDisposables[i].dispose(); + } + }; + + /** + * Determines whether the CompositeDisposable contains a specific disposable. + * @param {Mixed} item Disposable to search for. + * @returns {Boolean} true if the disposable was found; otherwise, false. + */ + CompositeDisposablePrototype.contains = function (item) { + return this.disposables.indexOf(item) !== -1; + }; + + /** + * Converts the existing CompositeDisposable to an array of disposables + * @returns {Array} An array of disposable objects. + */ + CompositeDisposablePrototype.toArray = function () { + return this.disposables.slice(0); + }; + + /** + * Provides a set of static methods for creating Disposables. + * + * @constructor + * @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once. + */ + var Disposable = Rx.Disposable = function (action) { + this.isDisposed = false; + this.action = action || noop; + }; + + /** Performs the task of cleaning up resources. */ + Disposable.prototype.dispose = function () { + if (!this.isDisposed) { + this.action(); + this.isDisposed = true; + } + }; + + /** + * Creates a disposable object that invokes the specified action when disposed. + * @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once. + * @return {Disposable} The disposable object that runs the given action upon disposal. + */ + var disposableCreate = Disposable.create = function (action) { return new Disposable(action); }; + + /** + * Gets the disposable that does nothing when disposed. + */ + var disposableEmpty = Disposable.empty = { dispose: noop }; + + var BooleanDisposable = (function () { + function BooleanDisposable (isSingle) { + this.isSingle = isSingle; + this.isDisposed = false; + this.current = null; + } + + var booleanDisposablePrototype = BooleanDisposable.prototype; + + /** + * Gets the underlying disposable. + * @return The underlying disposable. + */ + booleanDisposablePrototype.getDisposable = function () { + return this.current; + }; + + /** + * Sets the underlying disposable. + * @param {Disposable} value The new underlying disposable. + */ + booleanDisposablePrototype.setDisposable = function (value) { + if (this.current && this.isSingle) { + throw new Error('Disposable has already been assigned'); + } + + var shouldDispose = this.isDisposed, old; + if (!shouldDispose) { + old = this.current; + this.current = value; + } + if (old) { + old.dispose(); + } + if (shouldDispose && value) { + value.dispose(); + } + }; + + /** + * Disposes the underlying disposable as well as all future replacements. + */ + booleanDisposablePrototype.dispose = function () { + var old; + if (!this.isDisposed) { + this.isDisposed = true; + old = this.current; + this.current = null; + } + if (old) { + old.dispose(); + } + }; + + return BooleanDisposable; + }()); + + /** + * Represents a disposable resource which only allows a single assignment of its underlying disposable resource. + * If an underlying disposable resource has already been set, future attempts to set the underlying disposable resource will throw an Error. + */ + var SingleAssignmentDisposable = Rx.SingleAssignmentDisposable = (function (super_) { + inherits(SingleAssignmentDisposable, super_); + + function SingleAssignmentDisposable() { + super_.call(this, true); + } + + return SingleAssignmentDisposable; + }(BooleanDisposable)); + + /** + * Represents a disposable resource whose underlying disposable resource can be replaced by another disposable resource, causing automatic disposal of the previous underlying disposable resource. + */ + var SerialDisposable = Rx.SerialDisposable = (function (super_) { + inherits(SerialDisposable, super_); + + function SerialDisposable() { + super_.call(this, false); + } + + return SerialDisposable; + }(BooleanDisposable)); + + /** + * Represents a disposable resource that only disposes its underlying disposable resource when all dependent disposable objects have been disposed. + */ + var RefCountDisposable = Rx.RefCountDisposable = (function () { + + function InnerDisposable(disposable) { + this.disposable = disposable; + this.disposable.count++; + this.isInnerDisposed = false; + } + + InnerDisposable.prototype.dispose = function () { + if (!this.disposable.isDisposed) { + if (!this.isInnerDisposed) { + this.isInnerDisposed = true; + this.disposable.count--; + if (this.disposable.count === 0 && this.disposable.isPrimaryDisposed) { + this.disposable.isDisposed = true; + this.disposable.underlyingDisposable.dispose(); + } + } + } + }; + + /** + * Initializes a new instance of the RefCountDisposable with the specified disposable. + * @constructor + * @param {Disposable} disposable Underlying disposable. + */ + function RefCountDisposable(disposable) { + this.underlyingDisposable = disposable; + this.isDisposed = false; + this.isPrimaryDisposed = false; + this.count = 0; + } + + /** + * Disposes the underlying disposable only when all dependent disposables have been disposed + */ + RefCountDisposable.prototype.dispose = function () { + if (!this.isDisposed) { + if (!this.isPrimaryDisposed) { + this.isPrimaryDisposed = true; + if (this.count === 0) { + this.isDisposed = true; + this.underlyingDisposable.dispose(); + } + } + } + }; + + /** + * Returns a dependent disposable that when disposed decreases the refcount on the underlying disposable. + * @returns {Disposable} A dependent disposable contributing to the reference count that manages the underlying disposable's lifetime. + */ + RefCountDisposable.prototype.getDisposable = function () { + return this.isDisposed ? disposableEmpty : new InnerDisposable(this); + }; + + return RefCountDisposable; + })(); + + var ScheduledItem = Rx.internals.ScheduledItem = function (scheduler, state, action, dueTime, comparer) { + this.scheduler = scheduler; + this.state = state; + this.action = action; + this.dueTime = dueTime; + this.comparer = comparer || defaultSubComparer; + this.disposable = new SingleAssignmentDisposable(); + } + + ScheduledItem.prototype.invoke = function () { + this.disposable.setDisposable(this.invokeCore()); + }; + + ScheduledItem.prototype.compareTo = function (other) { + return this.comparer(this.dueTime, other.dueTime); + }; + + ScheduledItem.prototype.isCancelled = function () { + return this.disposable.isDisposed; + }; + + ScheduledItem.prototype.invokeCore = function () { + return this.action(this.scheduler, this.state); + }; + + /** Provides a set of static properties to access commonly used schedulers. */ + var Scheduler = Rx.Scheduler = (function () { + + function Scheduler(now, schedule, scheduleRelative, scheduleAbsolute) { + this.now = now; + this._schedule = schedule; + this._scheduleRelative = scheduleRelative; + this._scheduleAbsolute = scheduleAbsolute; + } + + function invokeRecImmediate(scheduler, pair) { + var state = pair.first, action = pair.second, group = new CompositeDisposable(), + recursiveAction = function (state1) { + action(state1, function (state2) { + var isAdded = false, isDone = false, + d = scheduler.scheduleWithState(state2, function (scheduler1, state3) { + if (isAdded) { + group.remove(d); + } else { + isDone = true; + } + recursiveAction(state3); + return disposableEmpty; + }); + if (!isDone) { + group.add(d); + isAdded = true; + } + }); + }; + recursiveAction(state); + return group; + } + + function invokeRecDate(scheduler, pair, method) { + var state = pair.first, action = pair.second, group = new CompositeDisposable(), + recursiveAction = function (state1) { + action(state1, function (state2, dueTime1) { + var isAdded = false, isDone = false, + d = scheduler[method].call(scheduler, state2, dueTime1, function (scheduler1, state3) { + if (isAdded) { + group.remove(d); + } else { + isDone = true; + } + recursiveAction(state3); + return disposableEmpty; + }); + if (!isDone) { + group.add(d); + isAdded = true; + } + }); + }; + recursiveAction(state); + return group; + } + + function invokeAction(scheduler, action) { + action(); + return disposableEmpty; + } + + var schedulerProto = Scheduler.prototype; + + /** + * Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation. + * @param {Number} period Period for running the work periodically. + * @param {Function} action Action to be executed. + * @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort). + */ + schedulerProto.schedulePeriodic = function (period, action) { + return this.schedulePeriodicWithState(null, period, function () { + action(); + }); + }; + + /** + * Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation. + * @param {Mixed} state Initial state passed to the action upon the first iteration. + * @param {Number} period Period for running the work periodically. + * @param {Function} action Action to be executed, potentially updating the state. + * @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort). + */ + schedulerProto.schedulePeriodicWithState = function (state, period, action) { + var s = state, id = setInterval(function () { + s = action(s); + }, period); + return disposableCreate(function () { + clearInterval(id); + }); + }; + + /** + * Schedules an action to be executed. + * @param {Function} action Action to execute. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.schedule = function (action) { + return this._schedule(action, invokeAction); + }; + + /** + * Schedules an action to be executed. + * @param state State passed to the action to be executed. + * @param {Function} action Action to be executed. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleWithState = function (state, action) { + return this._schedule(state, action); + }; + + /** + * Schedules an action to be executed after the specified relative due time. + * @param {Function} action Action to execute. + * @param {Number} dueTime Relative time after which to execute the action. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleWithRelative = function (dueTime, action) { + return this._scheduleRelative(action, dueTime, invokeAction); + }; + + /** + * Schedules an action to be executed after dueTime. + * @param {Mixed} state State passed to the action to be executed. + * @param {Function} action Action to be executed. + * @param {Number} dueTime Relative time after which to execute the action. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleWithRelativeAndState = function (state, dueTime, action) { + return this._scheduleRelative(state, dueTime, action); + }; + + /** + * Schedules an action to be executed at the specified absolute due time. + * @param {Function} action Action to execute. + * @param {Number} dueTime Absolute time at which to execute the action. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleWithAbsolute = function (dueTime, action) { + return this._scheduleAbsolute(action, dueTime, invokeAction); + }; + + /** + * Schedules an action to be executed at dueTime. + * @param {Mixed} state State passed to the action to be executed. + * @param {Function} action Action to be executed. + * @param {Number}dueTime Absolute time at which to execute the action. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleWithAbsoluteAndState = function (state, dueTime, action) { + return this._scheduleAbsolute(state, dueTime, action); + }; + + /** + * Schedules an action to be executed recursively. + * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleRecursive = function (action) { + return this.scheduleRecursiveWithState(action, function (_action, self) { + _action(function () { + self(_action); + }); + }); + }; + + /** + * Schedules an action to be executed recursively. + * @param {Mixed} state State passed to the action to be executed. + * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in recursive invocation state. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleRecursiveWithState = function (state, action) { + return this.scheduleWithState({ first: state, second: action }, function (s, p) { + return invokeRecImmediate(s, p); + }); + }; + + /** + * Schedules an action to be executed recursively after a specified relative due time. + * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified relative time. + * @param {Number}dueTime Relative time after which to execute the action for the first time. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleRecursiveWithRelative = function (dueTime, action) { + return this.scheduleRecursiveWithRelativeAndState(action, dueTime, function (_action, self) { + _action(function (dt) { + self(_action, dt); + }); + }); + }; + + /** + * Schedules an action to be executed recursively after a specified relative due time. + * @param {Mixed} state State passed to the action to be executed. + * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state. + * @param {Number}dueTime Relative time after which to execute the action for the first time. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleRecursiveWithRelativeAndState = function (state, dueTime, action) { + return this._scheduleRelative({ first: state, second: action }, dueTime, function (s, p) { + return invokeRecDate(s, p, 'scheduleWithRelativeAndState'); + }); + }; + + /** + * Schedules an action to be executed recursively at a specified absolute due time. + * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified absolute time. + * @param {Number}dueTime Absolute time at which to execute the action for the first time. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleRecursiveWithAbsolute = function (dueTime, action) { + return this.scheduleRecursiveWithAbsoluteAndState(action, dueTime, function (_action, self) { + _action(function (dt) { + self(_action, dt); + }); + }); + }; + + /** + * Schedules an action to be executed recursively at a specified absolute due time. + * @param {Mixed} state State passed to the action to be executed. + * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state. + * @param {Number}dueTime Absolute time at which to execute the action for the first time. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleRecursiveWithAbsoluteAndState = function (state, dueTime, action) { + return this._scheduleAbsolute({ first: state, second: action }, dueTime, function (s, p) { + return invokeRecDate(s, p, 'scheduleWithAbsoluteAndState'); + }); + }; + + /** Gets the current time according to the local machine's system clock. */ + Scheduler.now = defaultNow; + + /** + * Normalizes the specified TimeSpan value to a positive value. + * @param {Number} timeSpan The time span value to normalize. + * @returns {Number} The specified TimeSpan value if it is zero or positive; otherwise, 0 + */ + Scheduler.normalize = function (timeSpan) { + if (timeSpan < 0) { + timeSpan = 0; + } + return timeSpan; + }; + + return Scheduler; + }()); + + var normalizeTime = Scheduler.normalize; + + /** + * Gets a scheduler that schedules work immediately on the current thread. + */ + var immediateScheduler = Scheduler.immediate = (function () { + + function scheduleNow(state, action) { return action(this, state); } + + function scheduleRelative(state, dueTime, action) { + var dt = normalizeTime(dt); + while (dt - this.now() > 0) { } + return action(this, state); + } + + function scheduleAbsolute(state, dueTime, action) { + return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); + } + + return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); + }()); + + /** + * Gets a scheduler that schedules work as soon as possible on the current thread. + */ + var currentThreadScheduler = Scheduler.currentThread = (function () { + var queue; + + function runTrampoline (q) { + var item; + while (q.length > 0) { + item = q.dequeue(); + if (!item.isCancelled()) { + // Note, do not schedule blocking work! + while (item.dueTime - Scheduler.now() > 0) { + } + if (!item.isCancelled()) { + item.invoke(); + } + } + } + } + + function scheduleNow(state, action) { + return this.scheduleWithRelativeAndState(state, 0, action); + } + + function scheduleRelative(state, dueTime, action) { + var dt = this.now() + Scheduler.normalize(dueTime), + si = new ScheduledItem(this, state, action, dt), + t; + if (!queue) { + queue = new PriorityQueue(4); + queue.enqueue(si); + try { + runTrampoline(queue); + } catch (e) { + throw e; + } finally { + queue = null; + } + } else { + queue.enqueue(si); + } + return si.disposable; + } + + function scheduleAbsolute(state, dueTime, action) { + return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); + } + + var currentScheduler = new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); + currentScheduler.scheduleRequired = function () { return queue === null; }; + currentScheduler.ensureTrampoline = function (action) { + if (queue === null) { + return this.schedule(action); + } else { + return action(); + } + }; + + return currentScheduler; + }()); + + var SchedulePeriodicRecursive = Rx.internals.SchedulePeriodicRecursive = (function () { + function tick(command, recurse) { + recurse(0, this._period); + try { + this._state = this._action(this._state); + } catch (e) { + this._cancel.dispose(); + throw e; + } + } + + function SchedulePeriodicRecursive(scheduler, state, period, action) { + this._scheduler = scheduler; + this._state = state; + this._period = period; + this._action = action; + } + + SchedulePeriodicRecursive.prototype.start = function () { + var d = new SingleAssignmentDisposable(); + this._cancel = d; + d.setDisposable(this._scheduler.scheduleRecursiveWithRelativeAndState(0, this._period, tick.bind(this))); + + return d; + }; + + return SchedulePeriodicRecursive; + }()); + + + var scheduleMethod, clearMethod = noop; + (function () { + + var reNative = RegExp('^' + + String(toString) + .replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + .replace(/toString| for [^\]]+/g, '.*?') + '$' + ); + + var setImmediate = typeof (setImmediate = freeGlobal && moduleExports && freeGlobal.setImmediate) == 'function' && + !reNative.test(setImmediate) && setImmediate, + clearImmediate = typeof (clearImmediate = freeGlobal && moduleExports && freeGlobal.clearImmediate) == 'function' && + !reNative.test(clearImmediate) && clearImmediate; + + function postMessageSupported () { + // Ensure not in a worker + if (!root.postMessage || root.importScripts) { return false; } + var isAsync = false, + oldHandler = root.onmessage; + // Test for async + root.onmessage = function () { isAsync = true; }; + root.postMessage('','*'); + root.onmessage = oldHandler; + + return isAsync; + } + + // Use in order, nextTick, setImmediate, postMessage, MessageChannel, script readystatechanged, setTimeout + if (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]') { + scheduleMethod = process.nextTick; + } else if (typeof setImmediate === 'function') { + scheduleMethod = setImmediate; + clearMethod = clearImmediate; + } else if (postMessageSupported()) { + var MSG_PREFIX = 'ms.rx.schedule' + Math.random(), + tasks = {}, + taskId = 0; + + function onGlobalPostMessage(event) { + // Only if we're a match to avoid any other global events + if (typeof event.data === 'string' && event.data.substring(0, MSG_PREFIX.length) === MSG_PREFIX) { + var handleId = event.data.substring(MSG_PREFIX.length), + action = tasks[handleId]; + action(); + delete tasks[handleId]; + } + } + + if (root.addEventListener) { + root.addEventListener('message', onGlobalPostMessage, false); + } else { + root.attachEvent('onmessage', onGlobalPostMessage, false); + } + + scheduleMethod = function (action) { + var currentId = taskId++; + tasks[currentId] = action; + root.postMessage(MSG_PREFIX + currentId, '*'); + }; + } else if (!!root.MessageChannel) { + var channel = new root.MessageChannel(), + channelTasks = {}, + channelTaskId = 0; + + channel.port1.onmessage = function (event) { + var id = event.data, + action = channelTasks[id]; + action(); + delete channelTasks[id]; + }; + + scheduleMethod = function (action) { + var id = channelTaskId++; + channelTasks[id] = action; + channel.port2.postMessage(id); + }; + } else if ('document' in root && 'onreadystatechange' in root.document.createElement('script')) { + + scheduleMethod = function (action) { + var scriptElement = root.document.createElement('script'); + scriptElement.onreadystatechange = function () { + action(); + scriptElement.onreadystatechange = null; + scriptElement.parentNode.removeChild(scriptElement); + scriptElement = null; + }; + root.document.documentElement.appendChild(scriptElement); + }; + + } else { + scheduleMethod = function (action) { return setTimeout(action, 0); }; + clearMethod = clearTimeout; + } + }()); + + /** + * Gets a scheduler that schedules work via a timed callback based upon platform. + */ + var timeoutScheduler = Scheduler.timeout = (function () { + + function scheduleNow(state, action) { + var scheduler = this, + disposable = new SingleAssignmentDisposable(); + var id = scheduleMethod(function () { + if (!disposable.isDisposed) { + disposable.setDisposable(action(scheduler, state)); + } + }); + return new CompositeDisposable(disposable, disposableCreate(function () { + clearMethod(id); + })); + } + + function scheduleRelative(state, dueTime, action) { + var scheduler = this, + dt = Scheduler.normalize(dueTime); + if (dt === 0) { + return scheduler.scheduleWithState(state, action); + } + var disposable = new SingleAssignmentDisposable(); + var id = setTimeout(function () { + if (!disposable.isDisposed) { + disposable.setDisposable(action(scheduler, state)); + } + }, dt); + return new CompositeDisposable(disposable, disposableCreate(function () { + clearTimeout(id); + })); + } + + function scheduleAbsolute(state, dueTime, action) { + return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); + } + + return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); + })(); + + /** + * Represents a notification to an observer. + */ + var Notification = Rx.Notification = (function () { + function Notification(kind, hasValue) { + this.hasValue = hasValue == null ? false : hasValue; + this.kind = kind; + } + + var NotificationPrototype = Notification.prototype; + + /** + * Invokes the delegate corresponding to the notification or the observer's method corresponding to the notification and returns the produced result. + * + * @memberOf Notification + * @param {Any} observerOrOnNext Delegate to invoke for an OnNext notification or Observer to invoke the notification on.. + * @param {Function} onError Delegate to invoke for an OnError notification. + * @param {Function} onCompleted Delegate to invoke for an OnCompleted notification. + * @returns {Any} Result produced by the observation. + */ + NotificationPrototype.accept = function (observerOrOnNext, onError, onCompleted) { + if (arguments.length === 1 && typeof observerOrOnNext === 'object') { + return this._acceptObservable(observerOrOnNext); + } + return this._accept(observerOrOnNext, onError, onCompleted); + }; + + /** + * Returns an observable sequence with a single notification. + * + * @memberOf Notification + * @param {Scheduler} [scheduler] Scheduler to send out the notification calls on. + * @returns {Observable} The observable sequence that surfaces the behavior of the notification upon subscription. + */ + NotificationPrototype.toObservable = function (scheduler) { + var notification = this; + scheduler || (scheduler = immediateScheduler); + return new AnonymousObservable(function (observer) { + return scheduler.schedule(function () { + notification._acceptObservable(observer); + if (notification.kind === 'N') { + observer.onCompleted(); + } + }); + }); + }; + + return Notification; + })(); + + /** + * Creates an object that represents an OnNext notification to an observer. + * @param {Any} value The value contained in the notification. + * @returns {Notification} The OnNext notification containing the value. + */ + var notificationCreateOnNext = Notification.createOnNext = (function () { + + function _accept (onNext) { + return onNext(this.value); + } + + function _acceptObservable(observer) { + return observer.onNext(this.value); + } + + function toString () { + return 'OnNext(' + this.value + ')'; + } + + return function (value) { + var notification = new Notification('N', true); + notification.value = value; + notification._accept = _accept; + notification._acceptObservable = _acceptObservable; + notification.toString = toString; + return notification; + }; + }()); + + /** + * Creates an object that represents an OnError notification to an observer. + * @param {Any} error The exception contained in the notification. + * @returns {Notification} The OnError notification containing the exception. + */ + var notificationCreateOnError = Notification.createOnError = (function () { + + function _accept (onNext, onError) { + return onError(this.exception); + } + + function _acceptObservable(observer) { + return observer.onError(this.exception); + } + + function toString () { + return 'OnError(' + this.exception + ')'; + } + + return function (exception) { + var notification = new Notification('E'); + notification.exception = exception; + notification._accept = _accept; + notification._acceptObservable = _acceptObservable; + notification.toString = toString; + return notification; + }; + }()); + + /** + * Creates an object that represents an OnCompleted notification to an observer. + * @returns {Notification} The OnCompleted notification. + */ + var notificationCreateOnCompleted = Notification.createOnCompleted = (function () { + + function _accept (onNext, onError, onCompleted) { + return onCompleted(); + } + + function _acceptObservable(observer) { + return observer.onCompleted(); + } + + function toString () { + return 'OnCompleted()'; + } + + return function () { + var notification = new Notification('C'); + notification._accept = _accept; + notification._acceptObservable = _acceptObservable; + notification.toString = toString; + return notification; + }; + }()); + + var Enumerator = Rx.internals.Enumerator = function (next) { + this._next = next; + }; + + Enumerator.prototype.next = function () { + return this._next(); + }; + + Enumerator.prototype[$iterator$] = function () { return this; } + + var Enumerable = Rx.internals.Enumerable = function (iterator) { + this._iterator = iterator; + }; + + Enumerable.prototype[$iterator$] = function () { + return this._iterator(); + }; + + Enumerable.prototype.concat = function () { + var sources = this; + return new AnonymousObservable(function (observer) { + var e; + try { + e = sources[$iterator$](); + } catch(err) { + observer.onError(); + return; + } + + var isDisposed, + subscription = new SerialDisposable(); + var cancelable = immediateScheduler.scheduleRecursive(function (self) { + var currentItem; + if (isDisposed) { return; } + + try { + currentItem = e.next(); + } catch (ex) { + observer.onError(ex); + return; + } + + if (currentItem.done) { + observer.onCompleted(); + return; + } + + // Check if promise + var currentValue = currentItem.value; + isPromise(currentValue) && (currentValue = observableFromPromise(currentValue)); + + var d = new SingleAssignmentDisposable(); + subscription.setDisposable(d); + d.setDisposable(currentValue.subscribe( + observer.onNext.bind(observer), + observer.onError.bind(observer), + function () { self(); }) + ); + }); + + return new CompositeDisposable(subscription, cancelable, disposableCreate(function () { + isDisposed = true; + })); + }); + }; + + Enumerable.prototype.catchException = function () { + var sources = this; + return new AnonymousObservable(function (observer) { + var e; + try { + e = sources[$iterator$](); + } catch(err) { + observer.onError(); + return; + } + + var isDisposed, + lastException, + subscription = new SerialDisposable(); + var cancelable = immediateScheduler.scheduleRecursive(function (self) { + if (isDisposed) { return; } + + var currentItem; + try { + currentItem = e.next(); + } catch (ex) { + observer.onError(ex); + return; + } + + if (currentItem.done) { + if (lastException) { + observer.onError(lastException); + } else { + observer.onCompleted(); + } + return; + } + + // Check if promise + var currentValue = currentItem.value; + isPromise(currentValue) && (currentValue = observableFromPromise(currentValue)); + + var d = new SingleAssignmentDisposable(); + subscription.setDisposable(d); + d.setDisposable(currentValue.subscribe( + observer.onNext.bind(observer), + function (exn) { + lastException = exn; + self(); + }, + observer.onCompleted.bind(observer))); + }); + return new CompositeDisposable(subscription, cancelable, disposableCreate(function () { + isDisposed = true; + })); + }); + }; + + var enumerableRepeat = Enumerable.repeat = function (value, repeatCount) { + if (repeatCount == null) { repeatCount = -1; } + return new Enumerable(function () { + var left = repeatCount; + return new Enumerator(function () { + if (left === 0) { return doneEnumerator; } + if (left > 0) { left--; } + return { done: false, value: value }; + }); + }); + }; + + var enumerableFor = Enumerable.forEach = function (source, selector, thisArg) { + selector || (selector = identity); + return new Enumerable(function () { + var index = -1; + return new Enumerator( + function () { + return ++index < source.length ? + { done: false, value: selector.call(thisArg, source[index], index, source) } : + doneEnumerator; + }); + }); + }; + + /** + * Supports push-style iteration over an observable sequence. + */ + var Observer = Rx.Observer = function () { }; + + /** + * Creates a notification callback from an observer. + * + * @param observer Observer object. + * @returns The action that forwards its input notification to the underlying observer. + */ + Observer.prototype.toNotifier = function () { + var observer = this; + return function (n) { + return n.accept(observer); + }; + }; + + /** + * Hides the identity of an observer. + + * @returns An observer that hides the identity of the specified observer. + */ + Observer.prototype.asObserver = function () { + return new AnonymousObserver(this.onNext.bind(this), this.onError.bind(this), this.onCompleted.bind(this)); + }; + + /** + * Creates an observer from the specified OnNext, along with optional OnError, and OnCompleted actions. + * + * @static + * @memberOf Observer + * @param {Function} [onNext] Observer's OnNext action implementation. + * @param {Function} [onError] Observer's OnError action implementation. + * @param {Function} [onCompleted] Observer's OnCompleted action implementation. + * @returns {Observer} The observer object implemented using the given actions. + */ + var observerCreate = Observer.create = function (onNext, onError, onCompleted) { + onNext || (onNext = noop); + onError || (onError = defaultError); + onCompleted || (onCompleted = noop); + return new AnonymousObserver(onNext, onError, onCompleted); + }; + + /** + * Creates an observer from a notification callback. + * + * @static + * @memberOf Observer + * @param {Function} handler Action that handles a notification. + * @returns The observer object that invokes the specified handler using a notification corresponding to each message it receives. + */ + Observer.fromNotifier = function (handler) { + return new AnonymousObserver(function (x) { + return handler(notificationCreateOnNext(x)); + }, function (exception) { + return handler(notificationCreateOnError(exception)); + }, function () { + return handler(notificationCreateOnCompleted()); + }); + }; + + /** + * Abstract base class for implementations of the Observer class. + * This base class enforces the grammar of observers where OnError and OnCompleted are terminal messages. + */ + var AbstractObserver = Rx.internals.AbstractObserver = (function (_super) { + inherits(AbstractObserver, _super); + + /** + * Creates a new observer in a non-stopped state. + * + * @constructor + */ + function AbstractObserver() { + this.isStopped = false; + _super.call(this); + } + + /** + * Notifies the observer of a new element in the sequence. + * + * @memberOf AbstractObserver + * @param {Any} value Next element in the sequence. + */ + AbstractObserver.prototype.onNext = function (value) { + if (!this.isStopped) { + this.next(value); + } + }; + + /** + * Notifies the observer that an exception has occurred. + * + * @memberOf AbstractObserver + * @param {Any} error The error that has occurred. + */ + AbstractObserver.prototype.onError = function (error) { + if (!this.isStopped) { + this.isStopped = true; + this.error(error); + } + }; + + /** + * Notifies the observer of the end of the sequence. + */ + AbstractObserver.prototype.onCompleted = function () { + if (!this.isStopped) { + this.isStopped = true; + this.completed(); + } + }; + + /** + * Disposes the observer, causing it to transition to the stopped state. + */ + AbstractObserver.prototype.dispose = function () { + this.isStopped = true; + }; + + AbstractObserver.prototype.fail = function (e) { + if (!this.isStopped) { + this.isStopped = true; + this.error(e); + return true; + } + + return false; + }; + + return AbstractObserver; + }(Observer)); + + /** + * Class to create an Observer instance from delegate-based implementations of the on* methods. + */ + var AnonymousObserver = Rx.AnonymousObserver = (function (_super) { + inherits(AnonymousObserver, _super); + + /** + * Creates an observer from the specified OnNext, OnError, and OnCompleted actions. + * @param {Any} onNext Observer's OnNext action implementation. + * @param {Any} onError Observer's OnError action implementation. + * @param {Any} onCompleted Observer's OnCompleted action implementation. + */ + function AnonymousObserver(onNext, onError, onCompleted) { + _super.call(this); + this._onNext = onNext; + this._onError = onError; + this._onCompleted = onCompleted; + } + + /** + * Calls the onNext action. + * @param {Any} value Next element in the sequence. + */ + AnonymousObserver.prototype.next = function (value) { + this._onNext(value); + }; + + /** + * Calls the onError action. + * @param {Any} error The error that has occurred. + */ + AnonymousObserver.prototype.error = function (exception) { + this._onError(exception); + }; + + /** + * Calls the onCompleted action. + */ + AnonymousObserver.prototype.completed = function () { + this._onCompleted(); + }; + + return AnonymousObserver; + }(AbstractObserver)); + + var observableProto; + + /** + * Represents a push-style collection. + */ + var Observable = Rx.Observable = (function () { + + function Observable(subscribe) { + this._subscribe = subscribe; + } + + observableProto = Observable.prototype; + + /** + * Subscribes an observer to the observable sequence. + * + * @example + * 1 - source.subscribe(); + * 2 - source.subscribe(observer); + * 3 - source.subscribe(function (x) { console.log(x); }); + * 4 - source.subscribe(function (x) { console.log(x); }, function (err) { console.log(err); }); + * 5 - source.subscribe(function (x) { console.log(x); }, function (err) { console.log(err); }, function () { console.log('done'); }); + * @param {Mixed} [observerOrOnNext] The object that is to receive notifications or an action to invoke for each element in the observable sequence. + * @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence. + * @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence. + * @returns {Diposable} The source sequence whose subscriptions and unsubscriptions happen on the specified scheduler. + */ + observableProto.subscribe = observableProto.forEach = function (observerOrOnNext, onError, onCompleted) { + var subscriber = typeof observerOrOnNext === 'object' ? + observerOrOnNext : + observerCreate(observerOrOnNext, onError, onCompleted); + + return this._subscribe(subscriber); + }; + + return Observable; + })(); + + var ScheduledObserver = Rx.internals.ScheduledObserver = (function (_super) { + inherits(ScheduledObserver, _super); + + function ScheduledObserver(scheduler, observer) { + _super.call(this); + this.scheduler = scheduler; + this.observer = observer; + this.isAcquired = false; + this.hasFaulted = false; + this.queue = []; + this.disposable = new SerialDisposable(); + } + + ScheduledObserver.prototype.next = function (value) { + var self = this; + this.queue.push(function () { + self.observer.onNext(value); + }); + }; + + ScheduledObserver.prototype.error = function (exception) { + var self = this; + this.queue.push(function () { + self.observer.onError(exception); + }); + }; + + ScheduledObserver.prototype.completed = function () { + var self = this; + this.queue.push(function () { + self.observer.onCompleted(); + }); + }; + + ScheduledObserver.prototype.ensureActive = function () { + var isOwner = false, parent = this; + if (!this.hasFaulted && this.queue.length > 0) { + isOwner = !this.isAcquired; + this.isAcquired = true; + } + if (isOwner) { + this.disposable.setDisposable(this.scheduler.scheduleRecursive(function (self) { + var work; + if (parent.queue.length > 0) { + work = parent.queue.shift(); + } else { + parent.isAcquired = false; + return; + } + try { + work(); + } catch (ex) { + parent.queue = []; + parent.hasFaulted = true; + throw ex; + } + self(); + })); + } + }; + + ScheduledObserver.prototype.dispose = function () { + _super.prototype.dispose.call(this); + this.disposable.dispose(); + }; + + return ScheduledObserver; + }(AbstractObserver)); + + /** + * Creates a list from an observable sequence. + * @returns An observable sequence containing a single element with a list containing all the elements of the source sequence. + */ + observableProto.toArray = function () { + var self = this; + return new AnonymousObservable(function(observer) { + var arr = []; + return self.subscribe( + arr.push.bind(arr), + observer.onError.bind(observer), + function () { + observer.onNext(arr); + observer.onCompleted(); + }); + }); + }; + + /** + * Creates an observable sequence from a specified subscribe method implementation. + * + * @example + * var res = Rx.Observable.create(function (observer) { return function () { } ); + * var res = Rx.Observable.create(function (observer) { return Rx.Disposable.empty; } ); + * var res = Rx.Observable.create(function (observer) { } ); + * + * @param {Function} subscribe Implementation of the resulting observable sequence's subscribe method, returning a function that will be wrapped in a Disposable. + * @returns {Observable} The observable sequence with the specified implementation for the Subscribe method. + */ + Observable.create = Observable.createWithDisposable = function (subscribe) { + return new AnonymousObservable(subscribe); + }; + + /** + * Returns an observable sequence that invokes the specified factory function whenever a new observer subscribes. + * + * @example + * var res = Rx.Observable.defer(function () { return Rx.Observable.fromArray([1,2,3]); }); + * @param {Function} observableFactory Observable factory function to invoke for each observer that subscribes to the resulting sequence or Promise. + * @returns {Observable} An observable sequence whose observers trigger an invocation of the given observable factory function. + */ + var observableDefer = Observable.defer = function (observableFactory) { + return new AnonymousObservable(function (observer) { + var result; + try { + result = observableFactory(); + } catch (e) { + return observableThrow(e).subscribe(observer); + } + isPromise(result) && (result = observableFromPromise(result)); + return result.subscribe(observer); + }); + }; + + /** + * Returns an empty observable sequence, using the specified scheduler to send out the single OnCompleted message. + * + * @example + * var res = Rx.Observable.empty(); + * var res = Rx.Observable.empty(Rx.Scheduler.timeout); + * @param {Scheduler} [scheduler] Scheduler to send the termination call on. + * @returns {Observable} An observable sequence with no elements. + */ + var observableEmpty = Observable.empty = function (scheduler) { + scheduler || (scheduler = immediateScheduler); + return new AnonymousObservable(function (observer) { + return scheduler.schedule(function () { + observer.onCompleted(); + }); + }); + }; + + /** + * Converts an array to an observable sequence, using an optional scheduler to enumerate the array. + * + * @example + * var res = Rx.Observable.fromArray([1,2,3]); + * var res = Rx.Observable.fromArray([1,2,3], Rx.Scheduler.timeout); + * @param {Scheduler} [scheduler] Scheduler to run the enumeration of the input sequence on. + * @returns {Observable} The observable sequence whose elements are pulled from the given enumerable sequence. + */ + var observableFromArray = Observable.fromArray = function (array, scheduler) { + scheduler || (scheduler = currentThreadScheduler); + return new AnonymousObservable(function (observer) { + var count = 0, len = array.length; + return scheduler.scheduleRecursive(function (self) { + if (count < len) { + observer.onNext(array[count++]); + self(); + } else { + observer.onCompleted(); + } + }); + }); + }; + + /** + * Converts an iterable into an Observable sequence + * + * @example + * var res = Rx.Observable.fromIterable(new Map()); + * var res = Rx.Observable.fromIterable(new Set(), Rx.Scheduler.timeout); + * @param {Scheduler} [scheduler] Scheduler to run the enumeration of the input sequence on. + * @returns {Observable} The observable sequence whose elements are pulled from the given generator sequence. + */ + Observable.fromIterable = function (iterable, scheduler) { + scheduler || (scheduler = currentThreadScheduler); + return new AnonymousObservable(function (observer) { + var iterator; + try { + iterator = iterable[$iterator$](); + } catch (e) { + observer.onError(e); + return; + } + + return scheduler.scheduleRecursive(function (self) { + var next; + try { + next = iterator.next(); + } catch (err) { + observer.onError(err); + return; + } + + if (next.done) { + observer.onCompleted(); + } else { + observer.onNext(next.value); + self(); + } + }); + }); + }; + + /** + * 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) { + scheduler || (scheduler = currentThreadScheduler); + return new AnonymousObservable(function (observer) { + var first = true, state = initialState; + return scheduler.scheduleRecursive(function (self) { + var hasResult, result; + try { + if (first) { + first = false; + } else { + state = iterate(state); + } + hasResult = condition(state); + if (hasResult) { + result = resultSelector(state); + } + } catch (exception) { + observer.onError(exception); + return; + } + if (hasResult) { + observer.onNext(result); + self(); + } else { + observer.onCompleted(); + } + }); + }); + }; + + /** + * Returns a non-terminating observable sequence, which can be used to denote an infinite duration (e.g. when using reactive joins). + * @returns {Observable} An observable sequence whose observers will never get called. + */ + var observableNever = Observable.never = function () { + return new AnonymousObservable(function () { + return disposableEmpty; + }); + }; + + /** + * This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments. + * @example + * var res = Rx.Observable.of(1,2,3); + * @returns {Observable} The observable sequence whose elements are pulled from the given arguments. + */ + Observable.of = function () { + var len = arguments.length, args = new Array(len); + for(var i = 0; i < len; i++) { args[i] = arguments[i]; } + return observableFromArray(args); + }; + + /** + * This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments. + * @example + * var res = Rx.Observable.of(1,2,3); + * @param {Scheduler} scheduler A scheduler to use for scheduling the arguments. + * @returns {Observable} The observable sequence whose elements are pulled from the given arguments. + */ + var observableOf = Observable.ofWithScheduler = function (scheduler) { + var len = arguments.length - 1, args = new Array(len); + for(var i = 0; i < len; i++) { args[i] = arguments[i + 1]; } + return observableFromArray(args, scheduler); + }; + + /** + * Generates an observable sequence of integral numbers within a specified range, using the specified scheduler to send out observer messages. + * + * @example + * var res = Rx.Observable.range(0, 10); + * var res = Rx.Observable.range(0, 10, Rx.Scheduler.timeout); + * @param {Number} start The value of the first integer in the sequence. + * @param {Number} count The number of sequential integers to generate. + * @param {Scheduler} [scheduler] Scheduler to run the generator loop on. If not specified, defaults to Scheduler.currentThread. + * @returns {Observable} An observable sequence that contains a range of sequential integral numbers. + */ + Observable.range = function (start, count, scheduler) { + scheduler || (scheduler = currentThreadScheduler); + return new AnonymousObservable(function (observer) { + return scheduler.scheduleRecursiveWithState(0, function (i, self) { + if (i < count) { + observer.onNext(start + i); + self(i + 1); + } else { + observer.onCompleted(); + } + }); + }); + }; + + /** + * Generates an observable sequence that repeats the given element the specified number of times, using the specified scheduler to send out observer messages. + * + * @example + * var res = Rx.Observable.repeat(42); + * var res = Rx.Observable.repeat(42, 4); + * 3 - res = Rx.Observable.repeat(42, 4, Rx.Scheduler.timeout); + * 4 - res = Rx.Observable.repeat(42, null, Rx.Scheduler.timeout); + * @param {Mixed} value Element to repeat. + * @param {Number} repeatCount [Optiona] Number of times to repeat the element. If not specified, repeats indefinitely. + * @param {Scheduler} scheduler Scheduler to run the producer loop on. If not specified, defaults to Scheduler.immediate. + * @returns {Observable} An observable sequence that repeats the given element the specified number of times. + */ + Observable.repeat = function (value, repeatCount, scheduler) { + scheduler || (scheduler = currentThreadScheduler); + if (repeatCount == null) { + repeatCount = -1; + } + return observableReturn(value, scheduler).repeat(repeatCount); + }; + + /** + * Returns an observable sequence that contains a single element, using the specified scheduler to send out observer messages. + * There is an alias called 'just', and 'returnValue' for browsers 0) { + s = q.shift(); + subscribe(s); + } else { + activeCount--; + if (isStopped && activeCount === 0) { + observer.onCompleted(); + } + } + })); + }; + group.add(sources.subscribe(function (innerSource) { + if (activeCount < maxConcurrentOrOther) { + activeCount++; + subscribe(innerSource); + } else { + q.push(innerSource); + } + }, observer.onError.bind(observer), function () { + isStopped = true; + if (activeCount === 0) { + observer.onCompleted(); + } + })); + return group; + }); + }; + + /** + * Merges all the observable sequences into a single observable sequence. + * The scheduler is optional and if not specified, the immediate scheduler is used. + * + * @example + * 1 - merged = Rx.Observable.merge(xs, ys, zs); + * 2 - merged = Rx.Observable.merge([xs, ys, zs]); + * 3 - merged = Rx.Observable.merge(scheduler, xs, ys, zs); + * 4 - merged = Rx.Observable.merge(scheduler, [xs, ys, zs]); + * @returns {Observable} The observable sequence that merges the elements of the observable sequences. + */ + var observableMerge = Observable.merge = function () { + var scheduler, sources; + if (!arguments[0]) { + scheduler = immediateScheduler; + sources = slice.call(arguments, 1); + } else if (arguments[0].now) { + scheduler = arguments[0]; + sources = slice.call(arguments, 1); + } else { + scheduler = immediateScheduler; + sources = slice.call(arguments, 0); + } + if (Array.isArray(sources[0])) { + sources = sources[0]; + } + return observableFromArray(sources, scheduler).mergeObservable(); + }; + + /** + * Merges an observable sequence of observable sequences into an observable sequence. + * @returns {Observable} The observable sequence that merges the elements of the inner sequences. + */ + observableProto.mergeObservable = observableProto.mergeAll =function () { + var sources = this; + return new AnonymousObservable(function (observer) { + var group = new CompositeDisposable(), + isStopped = false, + m = new SingleAssignmentDisposable(); + + group.add(m); + m.setDisposable(sources.subscribe(function (innerSource) { + var innerSubscription = new SingleAssignmentDisposable(); + group.add(innerSubscription); + + // Check if Promise or Observable + if (isPromise(innerSource)) { + innerSource = observableFromPromise(innerSource); + } + + innerSubscription.setDisposable(innerSource.subscribe(function (x) { + observer.onNext(x); + }, observer.onError.bind(observer), function () { + group.remove(innerSubscription); + if (isStopped && group.length === 1) { observer.onCompleted(); } + })); + }, observer.onError.bind(observer), function () { + isStopped = true; + if (group.length === 1) { observer.onCompleted(); } + })); + return group; + }); + }; + + /** + * Returns the values from the source observable sequence only after the other observable sequence produces a value. + * @param {Observable | Promise} other The observable sequence or Promise that triggers propagation of elements of the source sequence. + * @returns {Observable} An observable sequence containing the elements of the source sequence starting from the point the other sequence triggered propagation. + */ + observableProto.skipUntil = function (other) { + var source = this; + return new AnonymousObservable(function (observer) { + var isOpen = false; + var disposables = new CompositeDisposable(source.subscribe(function (left) { + isOpen && observer.onNext(left); + }, observer.onError.bind(observer), function () { + isOpen && observer.onCompleted(); + })); + + isPromise(other) && (other = observableFromPromise(other)); + + var rightSubscription = new SingleAssignmentDisposable(); + disposables.add(rightSubscription); + rightSubscription.setDisposable(other.subscribe(function () { + isOpen = true; + rightSubscription.dispose(); + }, observer.onError.bind(observer), function () { + rightSubscription.dispose(); + })); + + return disposables; + }); + }; + + /** + * Transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence. + * @returns {Observable} The observable sequence that at any point in time produces the elements of the most recent inner observable sequence that has been received. + */ + observableProto['switch'] = observableProto.switchLatest = function () { + var sources = this; + return new AnonymousObservable(function (observer) { + var hasLatest = false, + innerSubscription = new SerialDisposable(), + isStopped = false, + latest = 0, + subscription = sources.subscribe(function (innerSource) { + var d = new SingleAssignmentDisposable(), id = ++latest; + hasLatest = true; + innerSubscription.setDisposable(d); + + // Check if Promise or Observable + if (isPromise(innerSource)) { + innerSource = observableFromPromise(innerSource); + } + + d.setDisposable(innerSource.subscribe(function (x) { + if (latest === id) { + observer.onNext(x); + } + }, function (e) { + if (latest === id) { + observer.onError(e); + } + }, function () { + if (latest === id) { + hasLatest = false; + if (isStopped) { + observer.onCompleted(); + } + } + })); + }, observer.onError.bind(observer), function () { + isStopped = true; + if (!hasLatest) { + observer.onCompleted(); + } + }); + return new CompositeDisposable(subscription, innerSubscription); + }); + }; + + /** + * Returns the values from the source observable sequence until the other observable sequence produces a value. + * @param {Observable | Promise} other Observable sequence or Promise that terminates propagation of elements of the source sequence. + * @returns {Observable} An observable sequence containing the elements of the source sequence up to the point the other sequence interrupted further propagation. + */ + observableProto.takeUntil = function (other) { + var source = this; + return new AnonymousObservable(function (observer) { + isPromise(other) && (other = observableFromPromise(other)); + return new CompositeDisposable( + source.subscribe(observer), + other.subscribe(observer.onCompleted.bind(observer), observer.onError.bind(observer), noop) + ); + }); + }; + + function zipArray(second, resultSelector) { + var first = this; + return new AnonymousObservable(function (observer) { + var index = 0, len = second.length; + return first.subscribe(function (left) { + if (index < len) { + var right = second[index++], result; + try { + result = resultSelector(left, right); + } catch (e) { + observer.onError(e); + return; + } + observer.onNext(result); + } else { + observer.onCompleted(); + } + }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); + }); + } + + /** + * Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences or an array have produced an element at a corresponding index. + * The last element in the arguments must be a function to invoke for each series of elements at corresponding indexes in the sources. + * + * @example + * 1 - res = obs1.zip(obs2, fn); + * 1 - res = x1.zip([1,2,3], fn); + * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + observableProto.zip = function () { + if (Array.isArray(arguments[0])) { + return zipArray.apply(this, arguments); + } + var parent = this, sources = slice.call(arguments), resultSelector = sources.pop(); + sources.unshift(parent); + return new AnonymousObservable(function (observer) { + var n = sources.length, + queues = arrayInitialize(n, function () { return []; }), + isDone = arrayInitialize(n, function () { return false; }); + + function next(i) { + var res, queuedValues; + if (queues.every(function (x) { return x.length > 0; })) { + try { + queuedValues = queues.map(function (x) { return x.shift(); }); + res = resultSelector.apply(parent, queuedValues); + } catch (ex) { + observer.onError(ex); + return; + } + observer.onNext(res); + } else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) { + observer.onCompleted(); + } + }; + + function done(i) { + isDone[i] = true; + if (isDone.every(function (x) { return x; })) { + observer.onCompleted(); + } + } + + var subscriptions = new Array(n); + for (var idx = 0; idx < n; idx++) { + (function (i) { + var source = sources[i], sad = new SingleAssignmentDisposable(); + isPromise(source) && (source = observableFromPromise(source)); + sad.setDisposable(source.subscribe(function (x) { + queues[i].push(x); + next(i); + }, observer.onError.bind(observer), function () { + done(i); + })); + subscriptions[i] = sad; + })(idx); + } + + return new CompositeDisposable(subscriptions); + }); + }; + /** + * Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index. + * @param arguments Observable sources. + * @param {Function} resultSelector Function to invoke for each series of elements at corresponding indexes in the sources. + * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + Observable.zip = function () { + var args = slice.call(arguments, 0), + first = args.shift(); + return first.zip.apply(first, args); + }; + + /** + * Merges the specified observable sequences into one observable sequence by emitting a list with the elements of the observable sequences at corresponding indexes. + * @param arguments Observable sources. + * @returns {Observable} An observable sequence containing lists of elements at corresponding indexes. + */ + Observable.zipArray = function () { + var sources = argsOrArray(arguments, 0); + return new AnonymousObservable(function (observer) { + var n = sources.length, + queues = arrayInitialize(n, function () { return []; }), + isDone = arrayInitialize(n, function () { return false; }); + + function next(i) { + if (queues.every(function (x) { return x.length > 0; })) { + var res = queues.map(function (x) { return x.shift(); }); + observer.onNext(res); + } else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) { + observer.onCompleted(); + return; + } + }; + + function done(i) { + isDone[i] = true; + if (isDone.every(identity)) { + observer.onCompleted(); + return; + } + } + + var subscriptions = new Array(n); + for (var idx = 0; idx < n; idx++) { + (function (i) { + subscriptions[i] = new SingleAssignmentDisposable(); + subscriptions[i].setDisposable(sources[i].subscribe(function (x) { + queues[i].push(x); + next(i); + }, observer.onError.bind(observer), function () { + done(i); + })); + })(idx); + } + + var compositeDisposable = new CompositeDisposable(subscriptions); + compositeDisposable.add(disposableCreate(function () { + for (var qIdx = 0, qLen = queues.length; qIdx < qLen; qIdx++) { + queues[qIdx] = []; + } + })); + return compositeDisposable; + }); + }; + + /** + * Hides the identity of an observable sequence. + * @returns {Observable} An observable sequence that hides the identity of the source sequence. + */ + observableProto.asObservable = function () { + var source = this; + return new AnonymousObservable(function (observer) { + return source.subscribe(observer); + }); + }; + + /** + * Dematerializes the explicit notification values of an observable sequence as implicit notifications. + * @returns {Observable} An observable sequence exhibiting the behavior corresponding to the source sequence's notification values. + */ + observableProto.dematerialize = function () { + var source = this; + return new AnonymousObservable(function (observer) { + return source.subscribe(function (x) { + return x.accept(observer); + }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); + }); + }; + + /** + * Returns an observable sequence that contains only distinct contiguous elements according to the keySelector and the comparer. + * + * var obs = observable.distinctUntilChanged(); + * var obs = observable.distinctUntilChanged(function (x) { return x.id; }); + * var obs = observable.distinctUntilChanged(function (x) { return x.id; }, function (x, y) { return x === y; }); + * + * @param {Function} [keySelector] A function to compute the comparison key for each element. If not provided, it projects the value. + * @param {Function} [comparer] Equality comparer for computed key values. If not provided, defaults to an equality comparer function. + * @returns {Observable} An observable sequence only containing the distinct contiguous elements, based on a computed key value, from the source sequence. + */ + observableProto.distinctUntilChanged = function (keySelector, comparer) { + var source = this; + keySelector || (keySelector = identity); + comparer || (comparer = defaultComparer); + return new AnonymousObservable(function (observer) { + var hasCurrentKey = false, currentKey; + return source.subscribe(function (value) { + var comparerEquals = false, key; + try { + key = keySelector(value); + } catch (exception) { + observer.onError(exception); + return; + } + if (hasCurrentKey) { + try { + comparerEquals = comparer(currentKey, key); + } catch (exception) { + observer.onError(exception); + return; + } + } + if (!hasCurrentKey || !comparerEquals) { + hasCurrentKey = true; + currentKey = key; + observer.onNext(value); + } + }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); + }); + }; + + /** + * Invokes an action for each element in the observable sequence and invokes an action upon graceful or exceptional termination of the observable sequence. + * This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline. + * + * @example + * var res = observable.doAction(observer); + * var res = observable.doAction(onNext); + * var res = observable.doAction(onNext, onError); + * var res = observable.doAction(onNext, onError, onCompleted); + * @param {Mixed} observerOrOnNext Action to invoke for each element in the observable sequence or an observer. + * @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function. + * @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function. + * @returns {Observable} The source sequence with the side-effecting behavior applied. + */ + observableProto['do'] = observableProto.doAction = function (observerOrOnNext, onError, onCompleted) { + var source = this, onNextFunc; + if (typeof observerOrOnNext === 'function') { + onNextFunc = observerOrOnNext; + } else { + onNextFunc = observerOrOnNext.onNext.bind(observerOrOnNext); + onError = observerOrOnNext.onError.bind(observerOrOnNext); + onCompleted = observerOrOnNext.onCompleted.bind(observerOrOnNext); + } + return new AnonymousObservable(function (observer) { + return source.subscribe(function (x) { + try { + onNextFunc(x); + } catch (e) { + observer.onError(e); + } + observer.onNext(x); + }, function (exception) { + if (!onError) { + observer.onError(exception); + } else { + try { + onError(exception); + } catch (e) { + observer.onError(e); + } + observer.onError(exception); + } + }, function () { + if (!onCompleted) { + observer.onCompleted(); + } else { + try { + onCompleted(); + } catch (e) { + observer.onError(e); + } + observer.onCompleted(); + } + }); + }); + }; + + /** + * Invokes a specified action after the source observable sequence terminates gracefully or exceptionally. + * + * @example + * var res = observable.finallyAction(function () { console.log('sequence ended'; }); + * @param {Function} finallyAction Action to invoke after the source observable sequence terminates. + * @returns {Observable} Source sequence with the action-invoking termination behavior applied. + */ + observableProto['finally'] = observableProto.finallyAction = function (action) { + var source = this; + return new AnonymousObservable(function (observer) { + var subscription; + try { + subscription = source.subscribe(observer); + } catch (e) { + action(); + throw e; + } + return disposableCreate(function () { + try { + subscription.dispose(); + } catch (e) { + throw e; + } finally { + action(); + } + }); + }); + }; + + /** + * Ignores all elements in an observable sequence leaving only the termination messages. + * @returns {Observable} An empty observable sequence that signals termination, successful or exceptional, of the source sequence. + */ + observableProto.ignoreElements = function () { + var source = this; + return new AnonymousObservable(function (observer) { + return source.subscribe(noop, observer.onError.bind(observer), observer.onCompleted.bind(observer)); + }); + }; + + /** + * Materializes the implicit notifications of an observable sequence as explicit notification values. + * @returns {Observable} An observable sequence containing the materialized notification values from the source sequence. + */ + observableProto.materialize = function () { + var source = this; + return new AnonymousObservable(function (observer) { + return source.subscribe(function (value) { + observer.onNext(notificationCreateOnNext(value)); + }, function (e) { + observer.onNext(notificationCreateOnError(e)); + observer.onCompleted(); + }, function () { + observer.onNext(notificationCreateOnCompleted()); + observer.onCompleted(); + }); + }); + }; + + /** + * Repeats the observable sequence a specified number of times. If the repeat count is not specified, the sequence repeats indefinitely. + * + * @example + * var res = repeated = source.repeat(); + * var res = repeated = source.repeat(42); + * @param {Number} [repeatCount] Number of times to repeat the sequence. If not provided, repeats the sequence indefinitely. + * @returns {Observable} The observable sequence producing the elements of the given sequence repeatedly. + */ + observableProto.repeat = function (repeatCount) { + return enumerableRepeat(this, repeatCount).concat(); + }; + + /** + * Repeats the source observable sequence the specified number of times or until it successfully terminates. If the retry count is not specified, it retries indefinitely. + * + * @example + * var res = retried = retry.repeat(); + * var res = retried = retry.repeat(42); + * @param {Number} [retryCount] Number of times to retry the sequence. If not provided, retry the sequence indefinitely. + * @returns {Observable} An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully. + */ + observableProto.retry = function (retryCount) { + return enumerableRepeat(this, retryCount).catchException(); + }; + + /** + * Applies an accumulator function over an observable sequence and returns each intermediate result. The optional seed value is used as the initial accumulator value. + * For aggregation behavior with no intermediate results, see Observable.aggregate. + * @example + * var res = source.scan(function (acc, x) { return acc + x; }); + * var res = source.scan(0, function (acc, x) { return acc + x; }); + * @param {Mixed} [seed] The initial accumulator value. + * @param {Function} accumulator An accumulator function to be invoked on each element. + * @returns {Observable} An observable sequence containing the accumulated values. + */ + observableProto.scan = function () { + var hasSeed = false, seed, accumulator, source = this; + if (arguments.length === 2) { + hasSeed = true; + seed = arguments[0]; + accumulator = arguments[1]; + } else { + accumulator = arguments[0]; + } + return new AnonymousObservable(function (observer) { + var hasAccumulation, accumulation, hasValue; + return source.subscribe ( + function (x) { + try { + if (!hasValue) { + hasValue = true; + } + + if (hasAccumulation) { + accumulation = accumulator(accumulation, x); + } else { + accumulation = hasSeed ? accumulator(seed, x) : x; + hasAccumulation = true; + } + } catch (e) { + observer.onError(e); + return; + } + + observer.onNext(accumulation); + }, + observer.onError.bind(observer), + function () { + if (!hasValue && hasSeed) { + observer.onNext(seed); + } + observer.onCompleted(); + } + ); + }); + }; + + /** + * Bypasses a specified number of elements at the end of an observable sequence. + * @description + * This operator accumulates a queue with a length enough to store the first `count` elements. As more elements are + * received, elements are taken from the front of the queue and produced on the result sequence. This causes elements to be delayed. + * @param count Number of elements to bypass at the end of the source sequence. + * @returns {Observable} An observable sequence containing the source sequence elements except for the bypassed ones at the end. + */ + observableProto.skipLast = function (count) { + var source = this; + return new AnonymousObservable(function (observer) { + var q = []; + return source.subscribe(function (x) { + q.push(x); + if (q.length > count) { + observer.onNext(q.shift()); + } + }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); + }); + }; + + /** + * Prepends a sequence of values to an observable sequence with an optional scheduler and an argument list of values to prepend. + * + * var res = source.startWith(1, 2, 3); + * var res = source.startWith(Rx.Scheduler.timeout, 1, 2, 3); + * + * @memberOf Observable# + * @returns {Observable} The source sequence prepended with the specified values. + */ + observableProto.startWith = function () { + var values, scheduler, start = 0; + if (!!arguments.length && 'now' in Object(arguments[0])) { + scheduler = arguments[0]; + start = 1; + } else { + scheduler = immediateScheduler; + } + values = slice.call(arguments, start); + return enumerableFor([observableFromArray(values, scheduler), this]).concat(); + }; + + /** + * Returns a specified number of contiguous elements from the end of an observable sequence, using an optional scheduler to drain the queue. + * + * @example + * var res = source.takeLast(5); + * var res = source.takeLast(5, Rx.Scheduler.timeout); + * + * @description + * This operator accumulates a buffer with a length enough to store elements count elements. Upon completion of + * the source sequence, this buffer is drained on the result sequence. This causes the elements to be delayed. + * @param {Number} count Number of elements to take from the end of the source sequence. + * @param {Scheduler} [scheduler] Scheduler used to drain the queue upon completion of the source sequence. + * @returns {Observable} An observable sequence containing the specified number of elements from the end of the source sequence. + */ + observableProto.takeLast = function (count, scheduler) { + return this.takeLastBuffer(count).selectMany(function (xs) { return observableFromArray(xs, scheduler); }); + }; + + /** + * Returns an array with the specified number of contiguous elements from the end of an observable sequence. + * + * @description + * This operator accumulates a buffer with a length enough to store count elements. Upon completion of the + * source sequence, this buffer is produced on the result sequence. + * @param {Number} count Number of elements to take from the end of the source sequence. + * @returns {Observable} An observable sequence containing a single array with the specified number of elements from the end of the source sequence. + */ + observableProto.takeLastBuffer = function (count) { + var source = this; + return new AnonymousObservable(function (observer) { + var q = []; + return source.subscribe(function (x) { + q.push(x); + if (q.length > count) { + q.shift(); + } + }, observer.onError.bind(observer), function () { + observer.onNext(q); + observer.onCompleted(); + }); + }); + }; + + function concatMap(selector) { + return this.map(function (x, i) { + var result = selector(x, i); + return isPromise(result) ? observableFromPromise(result) : result; + }).concatAll(); + } + + function concatMapObserver(onNext, onError, onCompleted) { + var source = this; + return new AnonymousObservable(function (observer) { + var index = 0; + + return source.subscribe( + function (x) { + observer.onNext(onNext(x, index++)); + }, + function (err) { + observer.onNext(onError(err)); + observer.completed(); + }, + function () { + observer.onNext(onCompleted()); + observer.onCompleted(); + }); + }).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.selectMany(function (x) { return Rx.Observable.range(0, x); }); + * Or: + * Projects each element of an observable sequence to an observable sequence, invokes the result selector for the source element and each of the corresponding inner sequence's elements, and merges the results into one observable sequence. + * + * var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); }, function (x, y) { return x + y; }); + * Or: + * Projects each element of the source observable sequence to the other observable sequence and merges the resulting observable sequences into one observable sequence. + * + * var res = source.selectMany(Rx.Observable.fromArray([1,2,3])); + * @param selector A transform function to apply to each element or an observable sequence to project each element from the + * source sequence onto which could be either an observable or Promise. + * @param {Function} [resultSelector] A transform function to apply to each element of the intermediate sequence. + * @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) { + if (resultSelector) { + return this.concatMap(function (x, i) { + var selectorResult = selector(x, i), + result = isPromise(selectorResult) ? observableFromPromise(selectorResult) : selectorResult; + + return result.map(function (y) { + return resultSelector(x, y, i); + }); + }); + } + if (typeof selector === 'function') { + return concatMap.call(this, selector); + } + return concatMap.call(this, function () { + return selector; + }); + }; + + /** + * Projects each element of an observable sequence into a new form by incorporating the element's index. + * @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element. + * @param {Any} [thisArg] Object to use as this when executing callback. + * @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source. + */ + observableProto.select = observableProto.map = function (selector, thisArg) { + var parent = this; + return new AnonymousObservable(function (observer) { + var count = 0; + return parent.subscribe(function (value) { + var result; + try { + result = selector.call(thisArg, value, count++, parent); + } catch (exception) { + observer.onError(exception); + return; + } + observer.onNext(result); + }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); + }); + }; + + /** + * Retrieves the value of a specified property from all elements in the Observable sequence. + * @param {String} property The property to pluck. + * @returns {Observable} Returns a new Observable sequence of property values. + */ + observableProto.pluck = function (property) { + return this.select(function (x) { return x[property]; }); + }; + + function selectMany(selector) { + return this.select(function (x, i) { + var result = selector(x, i); + return isPromise(result) ? observableFromPromise(result) : result; + }).mergeObservable(); + } + + function selectManyObserver(onNext, onError, onCompleted) { + var source = this; + return new AnonymousObservable(function (observer) { + var index = 0; + + return source.subscribe( + function (x) { + observer.onNext(onNext(x, index++)); + }, + function (err) { + observer.onNext(onError(err)); + observer.completed(); + }, + function () { + observer.onNext(onCompleted()); + observer.onCompleted(); + }); + }).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 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.selectMany = observableProto.flatMap = function (selector, resultSelector) { + if (resultSelector) { + return this.selectMany(function (x, i) { + var selectorResult = selector(x, i), + result = isPromise(selectorResult) ? observableFromPromise(selectorResult) : selectorResult; + + return result.select(function (y) { + return resultSelector(x, y, i); + }); + }); + } + if (typeof selector === 'function') { + return selectMany.call(this, selector); + } + return selectMany.call(this, function () { + return selector; + }); + }; + + /** + * Projects each element of an observable sequence into a new sequence of observable sequences by incorporating the element's index and then + * transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence. + * @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element. + * @param {Any} [thisArg] Object to use as this when executing callback. + * @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source producing an Observable of Observable sequences + * and that at any point in time produces the elements of the most recent inner observable sequence that has been received. + */ + observableProto.selectSwitch = observableProto.flatMapLatest = observableProto.switchMap = function (selector, thisArg) { + return this.select(selector, thisArg).switchLatest(); + }; + + /** + * Bypasses a specified number of elements in an observable sequence and then returns the remaining elements. + * @param {Number} count The number of elements to skip before returning the remaining elements. + * @returns {Observable} An observable sequence that contains the elements that occur after the specified index in the input sequence. + */ + observableProto.skip = function (count) { + if (count < 0) { + throw new Error(argumentOutOfRange); + } + var observable = this; + return new AnonymousObservable(function (observer) { + var remaining = count; + return observable.subscribe(function (x) { + if (remaining <= 0) { + observer.onNext(x); + } else { + remaining--; + } + }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); + }); + }; + + /** + * Bypasses elements in an observable sequence as long as a specified condition is true and then returns the remaining elements. + * The element's index is used in the logic of the predicate function. + * + * var res = source.skipWhile(function (value) { return value < 10; }); + * var res = source.skipWhile(function (value, index) { return value < 10 || index < 10; }); + * @param {Function} predicate A function to test each element for a condition; the second parameter of the function represents the index of the source element. + * @param {Any} [thisArg] Object to use as this when executing callback. + * @returns {Observable} An observable sequence that contains the elements from the input sequence starting at the first element in the linear series that does not pass the test specified by predicate. + */ + observableProto.skipWhile = function (predicate, thisArg) { + var source = this; + return new AnonymousObservable(function (observer) { + var i = 0, running = false; + return source.subscribe(function (x) { + if (!running) { + try { + running = !predicate.call(thisArg, x, i++, source); + } catch (e) { + observer.onError(e); + return; + } + } + if (running) { + observer.onNext(x); + } + }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); + }); + }; + + /** + * Returns a specified number of contiguous elements from the start of an observable sequence, using the specified scheduler for the edge case of take(0). + * + * var res = source.take(5); + * var res = source.take(0, Rx.Scheduler.timeout); + * @param {Number} count The number of elements to return. + * @param {Scheduler} [scheduler] Scheduler used to produce an OnCompleted message in case 0) { + now = scheduler.now(); + d = d + p; + if (d <= now) { + d = now + p; + } + } + observer.onNext(count++); + self(d); + }); + }); + } + + /** + * 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) { + scheduler || (scheduler = timeoutScheduler); + return observableTimerTimeSpanAndPeriod(period, period, scheduler); + }; + + /** + * Returns an observable sequence that produces a value after dueTime has elapsed and then after each period. + * + * @example + * var res = Rx.Observable.timer(5000); + * var res = Rx.Observable.timer(5000, 1000); + * var res = Rx.Observable.timer(5000, Rx.Scheduler.timeout); + * var res = Rx.Observable.timer(5000, 1000, Rx.Scheduler.timeout); + * + * @param {Number} dueTime 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; + scheduler || (scheduler = timeoutScheduler); + if (typeof periodOrScheduler === 'number') { + period = periodOrScheduler; + } else if (typeof periodOrScheduler === 'object' && 'now' in periodOrScheduler) { + scheduler = periodOrScheduler; + } + return period === undefined ? + observableTimerTimeSpan(dueTime, scheduler) : + observableTimerTimeSpanAndPeriod(dueTime, period, scheduler); + }; + + /** + * Time shifts the observable sequence by dueTime. The relative time intervals between the values are preserved. + * + * @example + * var res = Rx.Observable.delay(5000); + * var 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) { + scheduler || (scheduler = timeoutScheduler); + var source = this; + 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); + }); + }; + + /** + * Ignores values from an observable sequence which are followed by another value before dueTime. + * + * @example + * 1 - res = source.throttle(5000); // 5 seconds + * 2 - res = source.throttle(5000, scheduler); + * + * @param {Number} dueTime Duration of the throttle period for each value (specified as an integer denoting milliseconds). + * @param {Scheduler} [scheduler] Scheduler to run the throttle timers on. If not specified, the timeout scheduler is used. + * @returns {Observable} The throttled sequence. + */ + observableProto.throttle = function (dueTime, scheduler) { + scheduler || (scheduler = timeoutScheduler); + var source = this; + return this.throttleWithSelector(function () { return observableTimer(dueTime, scheduler); }) + }; + + /** + * 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; + scheduler || (scheduler = timeoutScheduler); + return observableDefer(function () { + var last = scheduler.now(); + return source.select(function (x) { + var now = scheduler.now(), span = now - last; + last = now; + return { + value: x, + interval: span + }; + }); + }); + }; + + /** + * Records the timestamp for each value in an observable sequence. + * + * @example + * 1 - res = source.timestamp(); // produces { value: x, timestamp: ts } + * 2 - res = source.timestamp(Rx.Scheduler.timeout); + * + * @param {Scheduler} [scheduler] Scheduler used to compute timestamps. If not specified, the timeout scheduler is used. + * @returns {Observable} An observable sequence with timestamp information on values. + */ + observableProto.timestamp = function (scheduler) { + scheduler || (scheduler = timeoutScheduler); + return this.select(function (x) { + return { + value: x, + timestamp: scheduler.now() + }; + }); + }; + + function sampleObservable(source, sampler) { + + return new AnonymousObservable(function (observer) { + var atEnd, value, hasValue; + + function sampleSubscribe() { + if (hasValue) { + hasValue = false; + observer.onNext(value); + } + if (atEnd) { + observer.onCompleted(); + } + } + + return new CompositeDisposable( + source.subscribe(function (newValue) { + hasValue = true; + value = newValue; + }, observer.onError.bind(observer), function () { + atEnd = true; + }), + sampler.subscribe(sampleSubscribe, observer.onError.bind(observer), sampleSubscribe) + ); + }); + } + + /** + * Samples the observable sequence at each interval. + * + * @example + * 1 - res = source.sample(sampleObservable); // Sampler tick sequence + * 2 - res = source.sample(5000); // 5 seconds + * 2 - res = source.sample(5000, Rx.Scheduler.timeout); // 5 seconds + * + * @param {Mixed} intervalOrSampler Interval at which to sample (specified as an integer denoting milliseconds) or Sampler Observable. + * @param {Scheduler} [scheduler] Scheduler to run the sampling timer on. If not specified, the timeout scheduler is used. + * @returns {Observable} Sampled observable sequence. + */ + observableProto.sample = function (intervalOrSampler, scheduler) { + scheduler || (scheduler = timeoutScheduler); + if (typeof intervalOrSampler === 'number') { + return sampleObservable(this, observableinterval(intervalOrSampler, scheduler)); + } + return sampleObservable(this, intervalOrSampler); + }; + + /** + * Returns the source observable sequence or the other observable sequence if dueTime elapses. + * + * @example + * 1 - res = source.timeout(new Date()); // As a date + * 2 - res = source.timeout(5000); // 5 seconds + * 3 - res = source.timeout(new Date(), Rx.Observable.returnValue(42)); // As a date and timeout observable + * 4 - res = source.timeout(5000, Rx.Observable.returnValue(42)); // 5 seconds and timeout observable + * 5 - res = source.timeout(new Date(), Rx.Observable.returnValue(42), Rx.Scheduler.timeout); // As a date and timeout observable + * 6 - res = source.timeout(5000, Rx.Observable.returnValue(42), Rx.Scheduler.timeout); // 5 seconds and timeout observable + * + * @param {Number} dueTime Absolute (specified as a Date object) or relative time (specified as an integer denoting milliseconds) when a timeout occurs. + * @param {Observable} [other] Sequence to return in case of a timeout. If not specified, a timeout error throwing sequence will be used. + * @param {Scheduler} [scheduler] Scheduler to run the timeout timers on. If not specified, the timeout scheduler is used. + * @returns {Observable} The source sequence switching to the other sequence in case of a timeout. + */ + observableProto.timeout = function (dueTime, other, scheduler) { + other || (other = observableThrow(new Error('Timeout'))); + scheduler || (scheduler = timeoutScheduler); + + var source = this, schedulerMethod = dueTime instanceof Date ? + 'scheduleWithAbsolute' : + 'scheduleWithRelative'; + + return new AnonymousObservable(function (observer) { + var id = 0, + original = new SingleAssignmentDisposable(), + subscription = new SerialDisposable(), + switched = false, + timer = new SerialDisposable(); + + subscription.setDisposable(original); + + var createTimer = function () { + var myId = id; + timer.setDisposable(scheduler[schedulerMethod](dueTime, function () { + if (id === myId) { + isPromise(other) && (other = observableFromPromise(other)); + subscription.setDisposable(other.subscribe(observer)); + } + })); + }; + + createTimer(); + + original.setDisposable(source.subscribe(function (x) { + if (!switched) { + id++; + observer.onNext(x); + createTimer(); + } + }, function (e) { + if (!switched) { + id++; + observer.onError(e); + } + }, function () { + if (!switched) { + id++; + observer.onCompleted(); + } + })); + return new CompositeDisposable(subscription, timer); + }); + }; + + /** + * Generates an observable sequence by iterating a state from an initial state until the condition fails. + * + * @example + * res = source.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) { + scheduler || (scheduler = timeoutScheduler); + return new AnonymousObservable(function (observer) { + var first = true, + hasResult = false, + result, + state = initialState, + time; + return scheduler.scheduleRecursiveWithRelative(0, function (self) { + if (hasResult) { + observer.onNext(result); + } + try { + if (first) { + first = false; + } else { + state = iterate(state); + } + hasResult = condition(state); + if (hasResult) { + result = resultSelector(state); + time = timeSelector(state); + } + } catch (e) { + observer.onError(e); + return; + } + if (hasResult) { + self(time); + } else { + observer.onCompleted(); + } + }); + }); + }; + + /** + * Time shifts the observable sequence by delaying the subscription. + * + * @example + * 1 - res = source.delaySubscription(5000); // 5s + * 2 - res = source.delaySubscription(5000, Rx.Scheduler.timeout); // 5 seconds + * + * @param {Number} dueTime Absolute or relative time to perform the subscription at. + * @param {Scheduler} [scheduler] Scheduler to run the subscription delay timer on. If not specified, the timeout scheduler is used. + * @returns {Observable} Time-shifted sequence. + */ + observableProto.delaySubscription = function (dueTime, scheduler) { + scheduler || (scheduler = timeoutScheduler); + return this.delayWithSelector(observableTimer(dueTime, scheduler), function () { return observableEmpty(); }); + }; + + /** + * Time shifts the observable sequence based on a subscription delay and a delay selector function for each element. + * + * @example + * 1 - res = source.delayWithSelector(function (x) { return Rx.Scheduler.timer(5000); }); // with selector only + * 1 - res = source.delayWithSelector(Rx.Observable.timer(2000), function (x) { return Rx.Observable.timer(x); }); // with delay and selector + * + * @param {Observable} [subscriptionDelay] Sequence indicating the delay for the subscription to the source. + * @param {Function} delayDurationSelector Selector function to retrieve a sequence indicating the delay for each given element. + * @returns {Observable} Time-shifted sequence. + */ + observableProto.delayWithSelector = function (subscriptionDelay, delayDurationSelector) { + var source = this, subDelay, selector; + if (typeof subscriptionDelay === 'function') { + selector = subscriptionDelay; + } else { + subDelay = subscriptionDelay; + selector = delayDurationSelector; + } + return new AnonymousObservable(function (observer) { + var delays = new CompositeDisposable(), atEnd = false, done = function () { + if (atEnd && delays.length === 0) { + observer.onCompleted(); + } + }, subscription = new SerialDisposable(), start = function () { + subscription.setDisposable(source.subscribe(function (x) { + var delay; + try { + delay = selector(x); + } catch (error) { + observer.onError(error); + return; + } + var d = new SingleAssignmentDisposable(); + delays.add(d); + d.setDisposable(delay.subscribe(function () { + observer.onNext(x); + delays.remove(d); + done(); + }, observer.onError.bind(observer), function () { + observer.onNext(x); + delays.remove(d); + done(); + })); + }, observer.onError.bind(observer), function () { + atEnd = true; + subscription.dispose(); + done(); + })); + }; + + if (!subDelay) { + start(); + } else { + subscription.setDisposable(subDelay.subscribe(function () { + start(); + }, observer.onError.bind(observer), function () { start(); })); + } + + return new CompositeDisposable(subscription, delays); + }); + }; + + /** + * Returns the source observable sequence, switching to the other observable sequence if a timeout is signaled. + * + * @example + * 1 - res = source.timeoutWithSelector(Rx.Observable.timer(500)); + * 2 - res = source.timeoutWithSelector(Rx.Observable.timer(500), function (x) { return Rx.Observable.timer(200); }); + * 3 - res = source.timeoutWithSelector(Rx.Observable.timer(500), function (x) { return Rx.Observable.timer(200); }, Rx.Observable.returnValue(42)); + * + * @param {Observable} [firstTimeout] Observable sequence that represents the timeout for the first element. If not provided, this defaults to Observable.never(). + * @param {Function} [timeoutDurationSelector] Selector to retrieve an observable sequence that represents the timeout between the current element and the next element. + * @param {Observable} [other] Sequence to return in case of a timeout. If not provided, this is set to Observable.throwException(). + * @returns {Observable} The source sequence switching to the other sequence in case of a timeout. + */ + observableProto.timeoutWithSelector = function (firstTimeout, timeoutdurationSelector, other) { + if (arguments.length === 1) { + timeoutdurationSelector = firstTimeout; + var firstTimeout = observableNever(); + } + other || (other = observableThrow(new Error('Timeout'))); + var source = this; + return new AnonymousObservable(function (observer) { + var subscription = new SerialDisposable(), timer = new SerialDisposable(), original = new SingleAssignmentDisposable(); + + subscription.setDisposable(original); + + var id = 0, switched = false, setTimer = function (timeout) { + var myId = id, timerWins = function () { + return id === myId; + }; + var d = new SingleAssignmentDisposable(); + timer.setDisposable(d); + d.setDisposable(timeout.subscribe(function () { + if (timerWins()) { + subscription.setDisposable(other.subscribe(observer)); + } + d.dispose(); + }, function (e) { + if (timerWins()) { + observer.onError(e); + } + }, function () { + if (timerWins()) { + subscription.setDisposable(other.subscribe(observer)); + } + })); + }; + + setTimer(firstTimeout); + var observerWins = function () { + var res = !switched; + if (res) { + id++; + } + return res; + }; + + original.setDisposable(source.subscribe(function (x) { + if (observerWins()) { + observer.onNext(x); + var timeout; + try { + timeout = timeoutdurationSelector(x); + } catch (e) { + observer.onError(e); + return; + } + setTimer(timeout); + } + }, function (e) { + if (observerWins()) { + observer.onError(e); + } + }, function () { + if (observerWins()) { + observer.onCompleted(); + } + })); + return new CompositeDisposable(subscription, timer); + }); + }; + + /** + * Ignores values from an observable sequence which are followed by another value within a computed throttle duration. + * + * @example + * 1 - res = source.delayWithSelector(function (x) { return Rx.Scheduler.timer(x + x); }); + * + * @param {Function} throttleDurationSelector Selector function to retrieve a sequence indicating the throttle duration for each given element. + * @returns {Observable} The throttled sequence. + */ + observableProto.throttleWithSelector = function (throttleDurationSelector) { + var source = this; + return new AnonymousObservable(function (observer) { + var value, hasValue = false, cancelable = new SerialDisposable(), id = 0, subscription = source.subscribe(function (x) { + var throttle; + try { + throttle = throttleDurationSelector(x); + } catch (e) { + observer.onError(e); + return; + } + hasValue = true; + value = x; + id++; + var currentid = id, d = new SingleAssignmentDisposable(); + cancelable.setDisposable(d); + d.setDisposable(throttle.subscribe(function () { + if (hasValue && id === currentid) { + observer.onNext(value); + } + hasValue = false; + d.dispose(); + }, observer.onError.bind(observer), function () { + if (hasValue && id === currentid) { + observer.onNext(value); + } + hasValue = false; + d.dispose(); + })); + }, function (e) { + cancelable.dispose(); + observer.onError(e); + hasValue = false; + id++; + }, function () { + cancelable.dispose(); + if (hasValue) { + observer.onNext(value); + } + observer.onCompleted(); + hasValue = false; + id++; + }); + return new CompositeDisposable(subscription, cancelable); + }); + }; + + /** + * Skips elements for the specified duration from the end of the observable source sequence, using the specified scheduler to run timers. + * + * 1 - res = source.skipLastWithTime(5000); + * 2 - res = source.skipLastWithTime(5000, scheduler); + * + * @description + * This operator accumulates a queue with a length enough to store elements received during the initial duration window. + * As more elements are received, elements older than the specified duration are taken from the queue and produced on the + * result sequence. This causes elements to be delayed with duration. + * @param {Number} duration Duration for skipping elements from the end of the sequence. + * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout + * @returns {Observable} An observable sequence with the elements skipped during the specified duration from the end of the source sequence. + */ + observableProto.skipLastWithTime = function (duration, scheduler) { + scheduler || (scheduler = timeoutScheduler); + var source = this; + return new AnonymousObservable(function (observer) { + var q = []; + return source.subscribe(function (x) { + var now = scheduler.now(); + q.push({ interval: now, value: x }); + while (q.length > 0 && now - q[0].interval >= duration) { + observer.onNext(q.shift().value); + } + }, observer.onError.bind(observer), function () { + var now = scheduler.now(); + while (q.length > 0 && now - q[0].interval >= duration) { + observer.onNext(q.shift().value); + } + observer.onCompleted(); + }); + }); + }; + + /** + * Returns elements within the specified duration from the end of the observable source sequence, using the specified schedulers to run timers and to drain the collected elements. + * + * @example + * 1 - res = source.takeLastWithTime(5000, [optional timer scheduler], [optional loop scheduler]); + * @description + * This operator accumulates a queue with a length enough to store elements received during the initial duration window. + * As more elements are received, elements older than the specified duration are taken from the queue and produced on the + * result sequence. This causes elements to be delayed with duration. + * @param {Number} duration Duration for taking elements from the end of the sequence. + * @param {Scheduler} [timerScheduler] Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. + * @param {Scheduler} [loopScheduler] Scheduler to drain the collected elements. If not specified, defaults to Rx.Scheduler.immediate. + * @returns {Observable} An observable sequence with the elements taken during the specified duration from the end of the source sequence. + */ + observableProto.takeLastWithTime = function (duration, timerScheduler, loopScheduler) { + return this.takeLastBufferWithTime(duration, timerScheduler).selectMany(function (xs) { return observableFromArray(xs, loopScheduler); }); + }; + + /** + * Returns an array with the elements within the specified duration from the end of the observable source sequence, using the specified scheduler to run timers. + * + * @example + * 1 - res = source.takeLastBufferWithTime(5000, [optional scheduler]); + * @description + * This operator accumulates a queue with a length enough to store elements received during the initial duration window. + * As more elements are received, elements older than the specified duration are taken from the queue and produced on the + * result sequence. This causes elements to be delayed with duration. + * @param {Number} duration Duration for taking elements from the end of the sequence. + * @param {Scheduler} scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. + * @returns {Observable} An observable sequence containing a single array with the elements taken during the specified duration from the end of the source sequence. + */ + observableProto.takeLastBufferWithTime = function (duration, scheduler) { + var source = this; + scheduler || (scheduler = timeoutScheduler); + return new AnonymousObservable(function (observer) { + var q = []; + + return source.subscribe(function (x) { + var now = scheduler.now(); + q.push({ interval: now, value: x }); + while (q.length > 0 && now - q[0].interval >= duration) { + q.shift(); + } + }, observer.onError.bind(observer), function () { + var now = scheduler.now(), res = []; + while (q.length > 0) { + var next = q.shift(); + if (now - next.interval <= duration) { + res.push(next.value); + } + } + + observer.onNext(res); + observer.onCompleted(); + }); + }); + }; + + /** + * Takes elements for the specified duration from the start of the observable source sequence, using the specified scheduler to run timers. + * + * @example + * 1 - res = source.takeWithTime(5000, [optional scheduler]); + * @description + * This operator accumulates a queue with a length enough to store elements received during the initial duration window. + * As more elements are received, elements older than the specified duration are taken from the queue and produced on the + * result sequence. This causes elements to be delayed with duration. + * @param {Number} duration Duration for taking elements from the start of the sequence. + * @param {Scheduler} scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. + * @returns {Observable} An observable sequence with the elements taken during the specified duration from the start of the source sequence. + */ + observableProto.takeWithTime = function (duration, scheduler) { + var source = this; + scheduler || (scheduler = timeoutScheduler); + return new AnonymousObservable(function (observer) { + var t = scheduler.scheduleWithRelative(duration, function () { + observer.onCompleted(); + }); + + return new CompositeDisposable(t, source.subscribe(observer)); + }); + }; + + /** + * Skips elements for the specified duration from the start of the observable source sequence, using the specified scheduler to run timers. + * + * @example + * 1 - res = source.skipWithTime(5000, [optional scheduler]); + * + * @description + * Specifying a zero value for duration doesn't guarantee no elements will be dropped from the start of the source sequence. + * This is a side-effect of the asynchrony introduced by the scheduler, where the action that causes callbacks from the source sequence to be forwarded + * may not execute immediately, despite the zero due time. + * + * Errors produced by the source sequence are always forwarded to the result sequence, even if the error occurs before the duration. + * @param {Number} duration Duration for skipping elements from the start of the sequence. + * @param {Scheduler} scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. + * @returns {Observable} An observable sequence with the elements skipped during the specified duration from the start of the source sequence. + */ + observableProto.skipWithTime = function (duration, scheduler) { + var source = this; + scheduler || (scheduler = timeoutScheduler); + return new AnonymousObservable(function (observer) { + var open = false, + t = scheduler.scheduleWithRelative(duration, function () { open = true; }), + d = source.subscribe(function (x) { + if (open) { + observer.onNext(x); + } + }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); + + return new CompositeDisposable(t, d); + }); + }; + + /** + * Skips elements from the observable source sequence until the specified start time, using the specified scheduler to run timers. + * Errors produced by the source sequence are always forwarded to the result sequence, even if the error occurs before the start time. + * + * @examples + * 1 - res = source.skipUntilWithTime(new Date(), [optional scheduler]); + * 2 - res = source.skipUntilWithTime(5000, [optional scheduler]); + * @param startTime Time to start taking elements from the source sequence. If this value is less than or equal to Date(), no elements will be skipped. + * @param scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. + * @returns {Observable} An observable sequence with the elements skipped until the specified start time. + */ + observableProto.skipUntilWithTime = function (startTime, scheduler) { + scheduler || (scheduler = timeoutScheduler); + var source = this, schedulerMethod = startTime instanceof Date ? + 'scheduleWithAbsolute' : + 'scheduleWithRelative'; + return new AnonymousObservable(function (observer) { + var open = false; + + return new CompositeDisposable( + scheduler[schedulerMethod](startTime, function () { open = true; }), + source.subscribe( + function (x) { open && observer.onNext(x); }, + observer.onError.bind(observer), + observer.onCompleted.bind(observer))); + }); + }; + + /** + * Takes elements for the specified duration until the specified end time, using the specified scheduler to run timers. + * + * @example + * 1 - res = source.takeUntilWithTime(new Date(), [optional scheduler]); + * 2 - res = source.takeUntilWithTime(5000, [optional scheduler]); + * @param {Number | Date} endTime Time to stop taking elements from the source sequence. If this value is less than or equal to new Date(), the result stream will complete immediately. + * @param {Scheduler} scheduler Scheduler to run the timer on. + * @returns {Observable} An observable sequence with the elements taken until the specified end time. + */ + observableProto.takeUntilWithTime = function (endTime, scheduler) { + scheduler || (scheduler = timeoutScheduler); + var source = this, schedulerMethod = endTime instanceof Date ? + 'scheduleWithAbsolute' : + 'scheduleWithRelative'; + return new AnonymousObservable(function (observer) { + return new CompositeDisposable(scheduler[schedulerMethod](endTime, function () { + observer.onCompleted(); + }), source.subscribe(observer)); + }); + }; + + var PausableObservable = (function (_super) { + + inherits(PausableObservable, _super); + + function subscribe(observer) { + var conn = this.source.publish(), + subscription = conn.subscribe(observer), + connection = disposableEmpty; + + var pausable = this.subject.distinctUntilChanged().subscribe(function (b) { + if (b) { + connection = conn.connect(); + } else { + connection.dispose(); + connection = disposableEmpty; + } + }); + + return new CompositeDisposable(subscription, connection, pausable); + } + + function PausableObservable(source, subject) { + this.source = source; + this.subject = subject || new Subject(); + this.isPaused = true; + _super.call(this, subscribe); + } + + PausableObservable.prototype.pause = function () { + if (this.isPaused === true){ + return; + } + this.isPaused = true; + this.subject.onNext(false); + }; + + PausableObservable.prototype.resume = function () { + if (this.isPaused === false){ + return; + } + this.isPaused = false; + this.subject.onNext(true); + }; + + return PausableObservable; + + }(Observable)); + + /** + * Pauses the underlying observable sequence based upon the observable sequence which yields true/false. + * @example + * var pauser = new Rx.Subject(); + * var source = Rx.Observable.interval(100).pausable(pauser); + * @param {Observable} pauser The observable sequence used to pause the underlying sequence. + * @returns {Observable} The observable sequence which is paused based upon the pauser. + */ + observableProto.pausable = function (pauser) { + return new PausableObservable(this, pauser); + }; + function combineLatestSource(source, subject, resultSelector) { + return new AnonymousObservable(function (observer) { + var n = 2, + hasValue = [false, false], + hasValueAll = false, + isDone = false, + values = new Array(n); + + function next(x, i) { + values[i] = x + var res; + hasValue[i] = true; + if (hasValueAll || (hasValueAll = hasValue.every(identity))) { + try { + res = resultSelector.apply(null, values); + } catch (ex) { + observer.onError(ex); + return; + } + observer.onNext(res); + } else if (isDone) { + observer.onCompleted(); + } + } + + return new CompositeDisposable( + source.subscribe( + function (x) { + next(x, 0); + }, + observer.onError.bind(observer), + function () { + isDone = true; + observer.onCompleted(); + }), + subject.subscribe( + function (x) { + next(x, 1); + }, + observer.onError.bind(observer)) + ); + }); + } + + var PausableBufferedObservable = (function (_super) { + + inherits(PausableBufferedObservable, _super); + + function subscribe(observer) { + var q = [], previous = true; + + var subscription = + combineLatestSource( + this.source, + this.subject.distinctUntilChanged(), + function (data, shouldFire) { + return { data: data, shouldFire: shouldFire }; + }) + .subscribe( + function (results) { + if (results.shouldFire && previous) { + observer.onNext(results.data); + } + if (results.shouldFire && !previous) { + while (q.length > 0) { + observer.onNext(q.shift()); + } + previous = true; + } else if (!results.shouldFire && !previous) { + q.push(results.data); + } else if (!results.shouldFire && previous) { + previous = false; + } + + }, + function (err) { + // Empty buffer before sending error + while (q.length > 0) { + observer.onNext(q.shift()); + } + observer.onError(err); + }, + function () { + // Empty buffer before sending completion + while (q.length > 0) { + observer.onNext(q.shift()); + } + observer.onCompleted(); + } + ); + + this.subject.onNext(false); + + return subscription; + } + + function PausableBufferedObservable(source, subject) { + this.source = source; + this.subject = subject || new Subject(); + this.isPaused = true; + _super.call(this, subscribe); + } + + PausableBufferedObservable.prototype.pause = function () { + if (this.isPaused === true){ + return; + } + this.isPaused = true; + this.subject.onNext(false); + }; + + PausableBufferedObservable.prototype.resume = function () { + if (this.isPaused === false){ + return; + } + this.isPaused = false; + this.subject.onNext(true); + }; + + return PausableBufferedObservable; + + }(Observable)); + + /** + * Pauses the underlying observable sequence based upon the observable sequence which yields true/false, + * and yields the values that were buffered while paused. + * @example + * var pauser = new Rx.Subject(); + * var source = Rx.Observable.interval(100).pausableBuffered(pauser); + * @param {Observable} pauser The observable sequence used to pause the underlying sequence. + * @returns {Observable} The observable sequence which is paused based upon the pauser. + */ + observableProto.pausableBuffered = function (subject) { + return new PausableBufferedObservable(this, subject); + }; + + /** + * Attaches a controller to the observable sequence with the ability to queue. + * @example + * var source = Rx.Observable.interval(100).controlled(); + * source.request(3); // Reads 3 values + * @param {Observable} pauser The observable sequence used to pause the underlying sequence. + * @returns {Observable} The observable sequence which is paused based upon the pauser. + */ + observableProto.controlled = function (enableQueue) { + if (enableQueue == null) { enableQueue = true; } + return new ControlledObservable(this, enableQueue); + }; + var ControlledObservable = (function (_super) { + + inherits(ControlledObservable, _super); + + function subscribe (observer) { + return this.source.subscribe(observer); + } + + function ControlledObservable (source, enableQueue) { + _super.call(this, subscribe); + this.subject = new ControlledSubject(enableQueue); + this.source = source.multicast(this.subject).refCount(); + } + + ControlledObservable.prototype.request = function (numberOfItems) { + if (numberOfItems == null) { numberOfItems = -1; } + return this.subject.request(numberOfItems); + }; + + return ControlledObservable; + + }(Observable)); + + var ControlledSubject = Rx.ControlledSubject = (function (_super) { + + function subscribe (observer) { + return this.subject.subscribe(observer); + } + + inherits(ControlledSubject, _super); + + function ControlledSubject(enableQueue) { + if (enableQueue == null) { + enableQueue = true; + } + + _super.call(this, subscribe); + this.subject = new Subject(); + this.enableQueue = enableQueue; + this.queue = enableQueue ? [] : null; + this.requestedCount = 0; + this.requestedDisposable = disposableEmpty; + this.error = null; + this.hasFailed = false; + this.hasCompleted = false; + this.controlledDisposable = disposableEmpty; + } + + addProperties(ControlledSubject.prototype, Observer, { + onCompleted: function () { + checkDisposed.call(this); + this.hasCompleted = true; + + if (!this.enableQueue || this.queue.length === 0) { + this.subject.onCompleted(); + } + }, + onError: function (error) { + checkDisposed.call(this); + this.hasFailed = true; + this.error = error; + + if (!this.enableQueue || this.queue.length === 0) { + this.subject.onError(error); + } + }, + onNext: function (value) { + checkDisposed.call(this); + var hasRequested = false; + + if (this.requestedCount === 0) { + if (this.enableQueue) { + this.queue.push(value); + } + } else { + if (this.requestedCount !== -1) { + if (this.requestedCount-- === 0) { + this.disposeCurrentRequest(); + } + } + hasRequested = true; + } + + if (hasRequested) { + this.subject.onNext(value); + } + }, + _processRequest: function (numberOfItems) { + if (this.enableQueue) { + //console.log('queue length', this.queue.length); + + while (this.queue.length >= numberOfItems && numberOfItems > 0) { + //console.log('number of items', numberOfItems); + this.subject.onNext(this.queue.shift()); + numberOfItems--; + } + + if (this.queue.length !== 0) { + return { numberOfItems: numberOfItems, returnValue: true }; + } else { + return { numberOfItems: numberOfItems, returnValue: false }; + } + } + + if (this.hasFailed) { + this.subject.onError(this.error); + this.controlledDisposable.dispose(); + this.controlledDisposable = disposableEmpty; + } else if (this.hasCompleted) { + this.subject.onCompleted(); + this.controlledDisposable.dispose(); + this.controlledDisposable = disposableEmpty; + } + + return { numberOfItems: numberOfItems, returnValue: false }; + }, + request: function (number) { + checkDisposed.call(this); + this.disposeCurrentRequest(); + var self = this, + r = this._processRequest(number); + + number = r.numberOfItems; + if (!r.returnValue) { + this.requestedCount = number; + this.requestedDisposable = disposableCreate(function () { + self.requestedCount = 0; + }); + + return this.requestedDisposable + } else { + return disposableEmpty; + } + }, + disposeCurrentRequest: function () { + this.requestedDisposable.dispose(); + this.requestedDisposable = disposableEmpty; + }, + + dispose: function () { + this.isDisposed = true; + this.error = null; + this.subject.dispose(); + this.requestedDisposable.dispose(); + } + }); + + return ControlledSubject; + }(Observable)); + /** + * Returns a new observable that triggers on the second and subsequent triggerings of the input observable. + * The Nth triggering of the input observable passes the arguments from the N-1th and Nth triggering as a pair. + * The argument passed to the N-1th triggering is held in hidden internal state until the Nth triggering occurs. + * @returns {Observable} An observable that triggers on successive pairs of observations from the input observable as an array. + */ + observableProto.pairwise = function () { + var source = this; + return new AnonymousObservable(function (observer) { + var previous, hasPrevious = false; + return source.subscribe( + function (x) { + if (hasPrevious) { + observer.onNext([previous, x]); + } else { + hasPrevious = true; + } + previous = x; + }, + observer.onError.bind(observer), + observer.onCompleted.bind(observer)); + }); + }; + /** + * Returns two observables which partition the observations of the source by the given function. + * The first will trigger observations for those values for which the predicate returns true. + * The second will trigger observations for those values where the predicate returns false. + * The predicate is executed once for each subscribed observer. + * Both also propagate all error observations arising from the source and each completes + * when the source completes. + * @param {Function} predicate + * The function to determine which output Observable will trigger a particular observation. + * @returns {Array} + * An array of observables. The first triggers when the predicate returns true, + * and the second triggers when the predicate returns false. + */ + observableProto.partition = function(predicate, thisArg) { + var published = this.publish().refCount(); + return [ + published.filter(predicate, thisArg), + published.filter(function (x, i, o) { return !predicate.call(thisArg, x, i, o); }) + ]; + }; + + /* + * Performs a exclusive waiting for the first to finish before subscribing to another observable. + * Observables that come in between subscriptions will be dropped on the floor. + * @returns {Observable} A exclusive observable with only the results that happen when subscribed. + */ + observableProto.exclusive = function () { + var sources = this; + return new AnonymousObservable(function (observer) { + var hasCurrent = false, + isStopped = false, + m = new SingleAssignmentDisposable(), + g = new CompositeDisposable(); + + g.add(m); + + m.setDisposable(sources.subscribe( + function (innerSource) { + if (!hasCurrent) { + hasCurrent = true; + + isPromise(innerSource) && (innerSource = observableFromPromise(innerSource)); + + var innerSubscription = new SingleAssignmentDisposable(); + g.add(innerSubscription); + + innerSubscription.setDisposable(innerSource.subscribe( + observer.onNext.bind(observer), + observer.onError.bind(observer), + function () { + g.remove(innerSubscription); + hasCurrent = false; + if (isStopped && g.length === 1) { + observer.onCompleted(); + } + })); + } + }, + observer.onError.bind(observer), + function () { + isStopped = true; + if (!hasCurrent && g.length === 1) { + observer.onCompleted(); + } + })); + + return g; + }); + }; + /* + * Performs a exclusive map waiting for the first to finish before subscribing to another observable. + * Observables that come in between subscriptions will be dropped on the floor. + * @param {Function} selector Selector to invoke for every item in the current subscription. + * @param {Any} [thisArg] An optional context to invoke with the selector parameter. + * @returns {Observable} An exclusive observable with only the results that happen when subscribed. + */ + observableProto.exclusiveMap = function (selector, thisArg) { + var sources = this; + return new AnonymousObservable(function (observer) { + var index = 0, + hasCurrent = false, + isStopped = true, + m = new SingleAssignmentDisposable(), + g = new CompositeDisposable(); + + g.add(m); + + m.setDisposable(sources.subscribe( + function (innerSource) { + + if (!hasCurrent) { + hasCurrent = true; + + innerSubscription = new SingleAssignmentDisposable(); + g.add(innerSubscription); + + isPromise(innerSource) && (innerSource = observableFromPromise(innerSource)); + + innerSubscription.setDisposable(innerSource.subscribe( + function (x) { + var result; + try { + result = selector.call(thisArg, x, index++, innerSource); + } catch (e) { + observer.onError(e); + return; + } + + observer.onNext(result); + }, + observer.onError.bind(observer), + function () { + g.remove(innerSubscription); + hasCurrent = false; + + if (isStopped && g.length === 1) { + observer.onCompleted(); + } + })); + } + }, + observer.onError.bind(observer), + function () { + isStopped = true; + if (g.length === 1 && !hasCurrent) { + observer.onCompleted(); + } + })); + return g; + }); + }; + var AnonymousObservable = Rx.AnonymousObservable = (function (__super__) { + inherits(AnonymousObservable, __super__); + + // Fix subscriber to check for undefined or function returned to decorate as Disposable + function fixSubscriber(subscriber) { + if (typeof subscriber === 'undefined') { + subscriber = disposableEmpty; + } else if (typeof subscriber === 'function') { + subscriber = disposableCreate(subscriber); + } + + return subscriber; + } + + function AnonymousObservable(subscribe) { + if (!(this instanceof AnonymousObservable)) { + return new AnonymousObservable(subscribe); + } + + function s(observer) { + var setDisposable = function () { + try { + autoDetachObserver.setDisposable(fixSubscriber(subscribe(autoDetachObserver))); + } catch (e) { + if (!autoDetachObserver.fail(e)) { + throw e; + } + } + }; + + var autoDetachObserver = new AutoDetachObserver(observer); + if (currentThreadScheduler.scheduleRequired()) { + currentThreadScheduler.schedule(setDisposable); + } else { + setDisposable(); + } + + return autoDetachObserver; + } + + __super__.call(this, s); + } + + return AnonymousObservable; + + }(Observable)); + + /** @private */ + var AutoDetachObserver = (function (_super) { + inherits(AutoDetachObserver, _super); + + function AutoDetachObserver(observer) { + _super.call(this); + this.observer = observer; + this.m = new SingleAssignmentDisposable(); + } + + var AutoDetachObserverPrototype = AutoDetachObserver.prototype; + + AutoDetachObserverPrototype.next = function (value) { + var noError = false; + try { + this.observer.onNext(value); + noError = true; + } catch (e) { + throw e; + } finally { + if (!noError) { + this.dispose(); + } + } + }; + + AutoDetachObserverPrototype.error = function (exn) { + try { + this.observer.onError(exn); + } catch (e) { + throw e; + } finally { + this.dispose(); + } + }; + + AutoDetachObserverPrototype.completed = function () { + try { + this.observer.onCompleted(); + } catch (e) { + throw e; + } finally { + this.dispose(); + } + }; + + AutoDetachObserverPrototype.setDisposable = function (value) { this.m.setDisposable(value); }; + AutoDetachObserverPrototype.getDisposable = function (value) { return this.m.getDisposable(); }; + /* @private */ + AutoDetachObserverPrototype.disposable = function (value) { + return arguments.length ? this.getDisposable() : setDisposable(value); + }; + + AutoDetachObserverPrototype.dispose = function () { + _super.prototype.dispose.call(this); + this.m.dispose(); + }; + + return AutoDetachObserver; + }(AbstractObserver)); + + /** @private */ + var InnerSubscription = function (subject, observer) { + this.subject = subject; + this.observer = observer; + }; + + /** + * @private + * @memberOf InnerSubscription + */ + InnerSubscription.prototype.dispose = function () { + if (!this.subject.isDisposed && this.observer !== null) { + var idx = this.subject.observers.indexOf(this.observer); + this.subject.observers.splice(idx, 1); + this.observer = null; + } + }; + + /** + * Represents an object that is both an observable sequence as well as an observer. + * Each notification is broadcasted to all subscribed observers. + */ + var Subject = Rx.Subject = (function (_super) { + function subscribe(observer) { + checkDisposed.call(this); + if (!this.isStopped) { + this.observers.push(observer); + return new InnerSubscription(this, observer); + } + if (this.exception) { + observer.onError(this.exception); + return disposableEmpty; + } + observer.onCompleted(); + return disposableEmpty; + } + + inherits(Subject, _super); + + /** + * Creates a subject. + * @constructor + */ + function Subject() { + _super.call(this, subscribe); + this.isDisposed = false, + this.isStopped = false, + this.observers = []; + } + + addProperties(Subject.prototype, Observer, { + /** + * Indicates whether the subject has observers subscribed to it. + * @returns {Boolean} Indicates whether the subject has observers subscribed to it. + */ + hasObservers: function () { + return this.observers.length > 0; + }, + /** + * Notifies all subscribed observers about the end of the sequence. + */ + onCompleted: function () { + checkDisposed.call(this); + if (!this.isStopped) { + var os = this.observers.slice(0); + this.isStopped = true; + for (var i = 0, len = os.length; i < len; i++) { + os[i].onCompleted(); + } + + this.observers = []; + } + }, + /** + * Notifies all subscribed observers about the exception. + * @param {Mixed} error The exception to send to all observers. + */ + onError: function (exception) { + checkDisposed.call(this); + if (!this.isStopped) { + var os = this.observers.slice(0); + this.isStopped = true; + this.exception = exception; + for (var i = 0, len = os.length; i < len; i++) { + os[i].onError(exception); + } + + this.observers = []; + } + }, + /** + * Notifies all subscribed observers about the arrival of the specified element in the sequence. + * @param {Mixed} value The value to send to all observers. + */ + onNext: function (value) { + checkDisposed.call(this); + if (!this.isStopped) { + var os = this.observers.slice(0); + for (var i = 0, len = os.length; i < len; i++) { + os[i].onNext(value); + } + } + }, + /** + * Unsubscribe all observers and release resources. + */ + dispose: function () { + this.isDisposed = true; + this.observers = null; + } + }); + + /** + * Creates a subject from the specified observer and observable. + * @param {Observer} observer The observer used to send messages to the subject. + * @param {Observable} observable The observable used to subscribe to messages sent from the subject. + * @returns {Subject} Subject implemented using the given observer and observable. + */ + Subject.create = function (observer, observable) { + return new AnonymousSubject(observer, observable); + }; + + return Subject; + }(Observable)); + + /** + * Represents the result of an asynchronous operation. + * The last value before the OnCompleted notification, or the error received through OnError, is sent to all subscribed observers. + */ + var AsyncSubject = Rx.AsyncSubject = (function (_super) { + + function subscribe(observer) { + checkDisposed.call(this); + + if (!this.isStopped) { + this.observers.push(observer); + return new InnerSubscription(this, observer); + } + + var ex = this.exception, + hv = this.hasValue, + v = this.value; + + if (ex) { + observer.onError(ex); + } else if (hv) { + observer.onNext(v); + observer.onCompleted(); + } else { + observer.onCompleted(); + } + + return disposableEmpty; + } + + inherits(AsyncSubject, _super); + + /** + * Creates a subject that can only receive one value and that value is cached for all future observations. + * @constructor + */ + function AsyncSubject() { + _super.call(this, subscribe); + + this.isDisposed = false; + this.isStopped = false; + this.value = null; + this.hasValue = false; + this.observers = []; + this.exception = null; + } + + addProperties(AsyncSubject.prototype, Observer, { + /** + * Indicates whether the subject has observers subscribed to it. + * @returns {Boolean} Indicates whether the subject has observers subscribed to it. + */ + hasObservers: function () { + checkDisposed.call(this); + return this.observers.length > 0; + }, + /** + * Notifies all subscribed observers about the end of the sequence, also causing the last received value to be sent out (if any). + */ + onCompleted: function () { + var o, i, len; + checkDisposed.call(this); + if (!this.isStopped) { + this.isStopped = true; + var os = this.observers.slice(0), + v = this.value, + hv = this.hasValue; + + if (hv) { + for (i = 0, len = os.length; i < len; i++) { + o = os[i]; + o.onNext(v); + o.onCompleted(); + } + } else { + for (i = 0, len = os.length; i < len; i++) { + os[i].onCompleted(); + } + } + + this.observers = []; + } + }, + /** + * Notifies all subscribed observers about the exception. + * @param {Mixed} error The exception to send to all observers. + */ + onError: function (exception) { + checkDisposed.call(this); + if (!this.isStopped) { + var os = this.observers.slice(0); + this.isStopped = true; + this.exception = exception; + + for (var i = 0, len = os.length; i < len; i++) { + os[i].onError(exception); + } + + this.observers = []; + } + }, + /** + * Sends a value to the subject. The last value received before successful termination will be sent to all subscribed and future observers. + * @param {Mixed} value The value to store in the subject. + */ + onNext: function (value) { + checkDisposed.call(this); + if (!this.isStopped) { + this.value = value; + this.hasValue = true; + } + }, + /** + * Unsubscribe all observers and release resources. + */ + dispose: function () { + this.isDisposed = true; + this.observers = null; + this.exception = null; + this.value = null; + } + }); + + return AsyncSubject; + }(Observable)); + + /** @private */ + var AnonymousSubject = (function (_super) { + inherits(AnonymousSubject, _super); + + function subscribe(observer) { + return this.observable.subscribe(observer); + } + + /** + * @private + * @constructor + */ + function AnonymousSubject(observer, observable) { + _super.call(this, subscribe); + this.observer = observer; + this.observable = observable; + } + + addProperties(AnonymousSubject.prototype, Observer, { + /** + * @private + * @memberOf AnonymousSubject# + */ + onCompleted: function () { + this.observer.onCompleted(); + }, + /** + * @private + * @memberOf AnonymousSubject# + */ + onError: function (exception) { + this.observer.onError(exception); + }, + /** + * @private + * @memberOf AnonymousSubject# + */ + onNext: function (value) { + this.observer.onNext(value); + } + }); + + return AnonymousSubject; + }(Observable)); + + /** + * Represents a value that changes over time. + * Observers can subscribe to the subject to receive the last (or initial) value and all subsequent notifications. + */ + var BehaviorSubject = Rx.BehaviorSubject = (function (_super) { + function subscribe(observer) { + checkDisposed.call(this); + if (!this.isStopped) { + this.observers.push(observer); + observer.onNext(this.value); + return new InnerSubscription(this, observer); + } + var ex = this.exception; + if (ex) { + observer.onError(ex); + } else { + observer.onCompleted(); + } + return disposableEmpty; + } + + inherits(BehaviorSubject, _super); + + /** + * @constructor + * Initializes a new instance of the BehaviorSubject class which creates a subject that caches its last value and starts with the specified value. + * @param {Mixed} value Initial value sent to observers when no other value has been received by the subject yet. + */ + function BehaviorSubject(value) { + _super.call(this, subscribe); + + this.value = value, + this.observers = [], + this.isDisposed = false, + this.isStopped = false, + this.exception = null; + } + + addProperties(BehaviorSubject.prototype, Observer, { + /** + * Indicates whether the subject has observers subscribed to it. + * @returns {Boolean} Indicates whether the subject has observers subscribed to it. + */ + hasObservers: function () { + return this.observers.length > 0; + }, + /** + * Notifies all subscribed observers about the end of the sequence. + */ + onCompleted: function () { + checkDisposed.call(this); + if (!this.isStopped) { + var os = this.observers.slice(0); + this.isStopped = true; + for (var i = 0, len = os.length; i < len; i++) { + os[i].onCompleted(); + } + + this.observers = []; + } + }, + /** + * Notifies all subscribed observers about the exception. + * @param {Mixed} error The exception to send to all observers. + */ + onError: function (error) { + checkDisposed.call(this); + if (!this.isStopped) { + var os = this.observers.slice(0); + this.isStopped = true; + this.exception = error; + + for (var i = 0, len = os.length; i < len; i++) { + os[i].onError(error); + } + + this.observers = []; + } + }, + /** + * Notifies all subscribed observers about the arrival of the specified element in the sequence. + * @param {Mixed} value The value to send to all observers. + */ + onNext: function (value) { + checkDisposed.call(this); + if (!this.isStopped) { + this.value = value; + var os = this.observers.slice(0); + for (var i = 0, len = os.length; i < len; i++) { + os[i].onNext(value); + } + } + }, + /** + * Unsubscribe all observers and release resources. + */ + dispose: function () { + this.isDisposed = true; + this.observers = null; + this.value = null; + this.exception = null; + } + }); + + return BehaviorSubject; + }(Observable)); + + /** + * Represents an object that is both an observable sequence as well as an observer. + * Each notification is broadcasted to all subscribed and future observers, subject to buffer trimming policies. + */ + var ReplaySubject = Rx.ReplaySubject = (function (_super) { + + function RemovableDisposable (subject, observer) { + this.subject = subject; + this.observer = observer; + }; + + RemovableDisposable.prototype.dispose = function () { + this.observer.dispose(); + if (!this.subject.isDisposed) { + var idx = this.subject.observers.indexOf(this.observer); + this.subject.observers.splice(idx, 1); + } + }; + + function subscribe(observer) { + var so = new ScheduledObserver(this.scheduler, observer), + subscription = new RemovableDisposable(this, so); + checkDisposed.call(this); + this._trim(this.scheduler.now()); + this.observers.push(so); + + var n = this.q.length; + + for (var i = 0, len = this.q.length; i < len; i++) { + so.onNext(this.q[i].value); + } + + if (this.hasError) { + n++; + so.onError(this.error); + } else if (this.isStopped) { + n++; + so.onCompleted(); + } + + so.ensureActive(n); + return subscription; + } + + inherits(ReplaySubject, _super); + + /** + * Initializes a new instance of the ReplaySubject class with the specified buffer size, window size and scheduler. + * @param {Number} [bufferSize] Maximum element count of the replay buffer. + * @param {Number} [windowSize] Maximum time length of the replay buffer. + * @param {Scheduler} [scheduler] Scheduler the observers are invoked on. + */ + function ReplaySubject(bufferSize, windowSize, scheduler) { + this.bufferSize = bufferSize == null ? Number.MAX_VALUE : bufferSize; + this.windowSize = windowSize == null ? Number.MAX_VALUE : windowSize; + this.scheduler = scheduler || currentThreadScheduler; + this.q = []; + this.observers = []; + this.isStopped = false; + this.isDisposed = false; + this.hasError = false; + this.error = null; + _super.call(this, subscribe); + } + + addProperties(ReplaySubject.prototype, Observer, { + /** + * Indicates whether the subject has observers subscribed to it. + * @returns {Boolean} Indicates whether the subject has observers subscribed to it. + */ + hasObservers: function () { + return this.observers.length > 0; + }, + /* @private */ + _trim: function (now) { + while (this.q.length > this.bufferSize) { + this.q.shift(); + } + while (this.q.length > 0 && (now - this.q[0].interval) > this.windowSize) { + this.q.shift(); + } + }, + /** + * Notifies all subscribed observers about the arrival of the specified element in the sequence. + * @param {Mixed} value The value to send to all observers. + */ + onNext: function (value) { + var observer; + checkDisposed.call(this); + if (!this.isStopped) { + var now = this.scheduler.now(); + this.q.push({ interval: now, value: value }); + this._trim(now); + + var o = this.observers.slice(0); + for (var i = 0, len = o.length; i < len; i++) { + observer = o[i]; + observer.onNext(value); + observer.ensureActive(); + } + } + }, + /** + * Notifies all subscribed observers about the exception. + * @param {Mixed} error The exception to send to all observers. + */ + onError: function (error) { + var observer; + checkDisposed.call(this); + if (!this.isStopped) { + this.isStopped = true; + this.error = error; + this.hasError = true; + var now = this.scheduler.now(); + this._trim(now); + var o = this.observers.slice(0); + for (var i = 0, len = o.length; i < len; i++) { + observer = o[i]; + observer.onError(error); + observer.ensureActive(); + } + this.observers = []; + } + }, + /** + * Notifies all subscribed observers about the end of the sequence. + */ + onCompleted: function () { + var observer; + checkDisposed.call(this); + if (!this.isStopped) { + this.isStopped = true; + var now = this.scheduler.now(); + this._trim(now); + var o = this.observers.slice(0); + for (var i = 0, len = o.length; i < len; i++) { + observer = o[i]; + observer.onCompleted(); + observer.ensureActive(); + } + this.observers = []; + } + }, + /** + * Unsubscribe all observers and release resources. + */ + dispose: function () { + this.isDisposed = true; + this.observers = null; + } + }); + + return ReplaySubject; + }(Observable)); + + if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) { + root.Rx = Rx; + + define(function() { + return Rx; + }); + } else if (freeExports && freeModule) { + // in Node.js or RingoJS + if (moduleExports) { + (freeModule.exports = Rx).Rx = Rx; + } else { + freeExports.Rx = Rx; + } + } else { + // in a browser or Rhino + root.Rx = Rx; + } +}.call(this)); \ No newline at end of file diff --git a/ajax/libs/rxjs/2.2.28/rx.lite.compat.min.js b/ajax/libs/rxjs/2.2.28/rx.lite.compat.min.js new file mode 100644 index 000000000..7b1cf88da --- /dev/null +++ b/ajax/libs/rxjs/2.2.28/rx.lite.compat.min.js @@ -0,0 +1,2 @@ +(function(t){function e(){if(this.isDisposed)throw Error(z)}function n(t){var e=typeof t;return t&&("function"==e||"object"==e)||!1}function r(t){var e=[];if(!n(t))return e;ce.nonEnumArgs&&t.length&&u(t)&&(t=he.call(t));var r=ce.enumPrototypes&&"function"==typeof t,i=ce.enumErrorProps&&(t===ne||t instanceof Error);for(var o in t)r&&"prototype"==o||i&&("message"==o||"name"==o)||e.push(o);if(ce.nonEnumShadows&&t!==re){var s=t.constructor,c=-1,a=se.length;if(t===(s&&s.prototype))var h=t===stringProto?G:t===ne?$:Y.call(t),l=ue[h];for(;a>++c;)o=se[c],l&&l[o]||!te.call(t,o)||e.push(o)}return e}function i(t,e,n){for(var r=-1,i=n(t),o=i.length;o>++r;){var s=i[r];if(e(t[s],s,t)===!1)break}return t}function o(t,e){return i(t,e,r)}function s(t){return"function"!=typeof t.toString&&"string"==typeof(t+"")}function u(t){return t&&"object"==typeof t?Y.call(t)==B:!1}function c(t){return"function"==typeof t||!1}function a(e,n,r,i){if(e===n)return 0!==e||1/e==1/n;var h=typeof e,l=typeof n;if(e===e&&(null==e||null==n||"function"!=h&&"object"!=h&&"function"!=l&&"object"!=l))return!1;var f=Y.call(e),p=Y.call(n);if(f==B&&(f=Z),p==B&&(p=Z),f!=p)return!1;switch(f){case Q:case H:return+e==+n;case J:return e!=+e?n!=+n:0==e?1/e==1/n:e==+n;case X:case G:return e==n+""}var d=f==U;if(!d){if(f!=Z||!ce.nodeClass&&(s(e)||s(n)))return!1;var b=!ce.argsObject&&u(e)?Object:e.constructor,v=!ce.argsObject&&u(n)?Object:n.constructor;if(!(b==v||te.call(e,"constructor")&&te.call(n,"constructor")||c(b)&&b instanceof b&&c(v)&&v instanceof v||!("constructor"in e&&"constructor"in n)))return!1}r||(r=[]),i||(i=[]);for(var m=r.length;m--;)if(r[m]==e)return i[m]==n;var y=0;if(result=!0,r.push(e),i.push(n),d){if(m=e.length,y=n.length,result=y==m)for(;y--;){var w=n[y];if(!(result=a(e[y],w,r,i)))break}}else o(n,function(n,o,s){return te.call(s,o)?(y++,result=te.call(e,o)&&a(e[o],n,r,i)):t}),result&&o(e,function(e,n,r){return te.call(r,n)?result=--y>-1:t});return r.pop(),i.pop(),result}function h(t,e){return 1===t.length&&Array.isArray(t[e])?t[e]:he.call(t)}function l(t,e){for(var n=Array(t),r=0;t>r;r++)n[r]=e();return n}function f(e,n){return new mn(function(r){var i=new De,o=new Se;return o.setDisposable(i),i.setDisposable(e.subscribe(r.onNext.bind(r),function(e){var i,s;try{s=n(e)}catch(u){return r.onError(u),t}L(s)&&(s=an(s)),i=new De,o.setDisposable(i),i.setDisposable(s.subscribe(r))},r.onCompleted.bind(r))),o})}function p(e,n){var r=this;return new mn(function(i){var o=0,s=e.length;return r.subscribe(function(r){if(s>o){var u,c=e[o++];try{u=n(r,c)}catch(a){return i.onError(a),t}i.onNext(u)}else i.onCompleted()},i.onError.bind(i),i.onCompleted.bind(i))})}function d(t){return this.map(function(e,n){var r=t(e,n);return L(r)?an(r):r}).concatAll()}function b(t){return this.select(function(e,n){var r=t(e,n);return L(r)?an(r):r}).mergeObservable()}function v(t){var e=function(){this.cancelBubble=!0},n=function(){if(this.bubbledKeyCode=this.keyCode,this.ctrlKey)try{this.keyCode=0}catch(t){}this.defaultPrevented=!0,this.returnValue=!1,this.modified=!0};if(t||(t=S.event),!t.target)switch(t.target=t.target||t.srcElement,"mouseover"==t.type&&(t.relatedTarget=t.fromElement),"mouseout"==t.type&&(t.relatedTarget=t.toElement),t.stopPropagation||(t.stopPropagation=e,t.preventDefault=n),t.type){case"keypress":var r="charCode"in t?t.charCode:t.keyCode;10==r?(r=0,t.keyCode=13):13==r||27==r?r=0:3==r&&(r=99),t.charCode=r,t.keyChar=t.charCode?String.fromCharCode(t.charCode):""}return t}function m(t,e,n){if(t.addListener)return t.addListener(e,n),Ee(function(){t.removeListener(e,n)});if(t.addEventListener)return t.addEventListener(e,n,!1),Ee(function(){t.removeEventListener(e,n,!1)});if(t.attachEvent){var r=function(t){n(v(t))};return t.attachEvent("on"+e,r),Ee(function(){t.detachEvent("on"+e,r)})}return t["on"+e]=n,Ee(function(){t["on"+e]=null})}function y(t,e,n){var r=new ye;if("function"==typeof t.item&&"number"==typeof t.length)for(var i=0,o=t.length;o>i;i++)r.add(y(t.item(i),e,n));else t&&r.add(m(t,e,n));return r}function w(t,e){var n=_e(t);return new mn(function(t){return e.scheduleWithRelative(n,function(){t.onNext(0),t.onCompleted()})})}function g(t,e,n){return t===e?new mn(function(t){return n.schedulePeriodicWithState(0,e,function(e){return t.onNext(e),e+1})}):Je(function(){return E(n.now()+t,e,n)})}function E(t,e,n){var r=_e(e);return new mn(function(e){var i=0,o=t;return n.scheduleRecursiveWithAbsolute(o,function(t){var s;r>0&&(s=n.now(),o+=r,s>=o&&(o=s+r)),e.onNext(i++),t(o)})})}function x(t,e){return new mn(function(n){function r(){s&&(s=!1,n.onNext(o)),i&&n.onCompleted()}var i,o,s;return new ye(t.subscribe(function(t){s=!0,o=t},n.onError.bind(n),function(){i=!0}),e.subscribe(r,n.onError.bind(n),r))})}function C(e,n,r){return new mn(function(i){function o(e,n){h[n]=e;var o;if(u[n]=!0,c||(c=u.every(W))){try{o=r.apply(null,h)}catch(s){return i.onError(s),t}i.onNext(o)}else a&&i.onCompleted()}var s=2,u=[!1,!1],c=!1,a=!1,h=Array(s);return new ye(e.subscribe(function(t){o(t,0)},i.onError.bind(i),function(){a=!0,i.onCompleted()}),n.subscribe(function(t){o(t,1)},i.onError.bind(i)))})}var D={"boolean":!1,"function":!0,object:!0,number:!1,string:!1,undefined:!1},S=D[typeof window]&&window||this,N=D[typeof exports]&&exports&&!exports.nodeType&&exports,A=D[typeof module]&&module&&!module.nodeType&&module,_=A&&A.exports===N&&N,O=D[typeof global]&&global;!O||O.global!==O&&O.window!==O||(S=O);var j={internals:{},config:{Promise:S.Promise},helpers:{}},R=j.helpers.noop=function(){},W=j.helpers.identity=function(t){return t},k=(j.helpers.pluck=function(t){return function(e){return e[t]}},j.helpers.just=function(t){return function(){return t}},j.helpers.defaultNow=function(){return Date.now?Date.now:function(){return+new Date}}()),q=j.helpers.defaultComparer=function(t,e){return ae(t,e)},P=j.helpers.defaultSubComparer=function(t,e){return t>e?1:e>t?-1:0},T=(j.helpers.defaultKeySerializer=function(t){return""+t},j.helpers.defaultError=function(t){throw t}),L=j.helpers.isPromise=function(t){return!!t&&"function"==typeof t.then&&t.then!==j.Observable.prototype.then};j.helpers.asArray=function(){return Array.prototype.slice.call(arguments)},j.helpers.not=function(t){return!t};var V="Argument out of range",z="Object has been disposed",M="object"==typeof Symbol&&Symbol.iterator||"_es6shim_iterator_";S.Set&&"function"==typeof(new S.Set)["@@iterator"]&&(M="@@iterator");var I,F={done:!0,value:t},B="[object Arguments]",U="[object Array]",Q="[object Boolean]",H="[object Date]",$="[object Error]",K="[object Function]",J="[object Number]",Z="[object Object]",X="[object RegExp]",G="[object String]",Y=Object.prototype.toString,te=Object.prototype.hasOwnProperty,ee=Y.call(arguments)==B,ne=Error.prototype,re=Object.prototype,ie=re.propertyIsEnumerable;try{I=!(Y.call(document)==Z&&!({toString:0}+""))}catch(oe){I=!0}var se=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],ue={};ue[U]=ue[H]=ue[J]={constructor:!0,toLocaleString:!0,toString:!0,valueOf:!0},ue[Q]=ue[G]={constructor:!0,toString:!0,valueOf:!0},ue[$]=ue[K]=ue[X]={constructor:!0,toString:!0},ue[Z]={constructor:!0};var ce={};(function(){var t=function(){this.x=1},e=[];t.prototype={valueOf:1,y:1};for(var n in new t)e.push(n);for(n in arguments);ce.enumErrorProps=ie.call(ne,"message")||ie.call(ne,"name"),ce.enumPrototypes=ie.call(t,"prototype"),ce.nonEnumArgs=0!=n,ce.nonEnumShadows=!/valueOf/.test(e)})(1),ee||(u=function(t){return t&&"object"==typeof t?te.call(t,"callee"):!1}),c(/x/)&&(c=function(t){return"function"==typeof t&&Y.call(t)==K});var ae=j.internals.isEqual=function(t,e){return a(t,e,[],[])},he=Array.prototype.slice;({}).hasOwnProperty;var le=this.inherits=j.internals.inherits=function(t,e){function n(){this.constructor=t}n.prototype=e.prototype,t.prototype=new n},fe=j.internals.addProperties=function(t){for(var e=he.call(arguments,1),n=0,r=e.length;r>n;n++){var i=e[n];for(var o in i)t[o]=i[o]}};j.internals.addRef=function(t,e){return new mn(function(n){return new ye(e.getDisposable(),t.subscribe(n))})},Function.prototype.bind||(Function.prototype.bind=function(t){var e=this,n=he.call(arguments,1),r=function(){function i(){}if(this instanceof r){i.prototype=e.prototype;var o=new i,s=e.apply(o,n.concat(he.call(arguments)));return Object(s)===s?s:o}return e.apply(t,n.concat(he.call(arguments)))};return r});var pe=Object("a"),de="a"!=pe[0]||!(0 in pe);Array.prototype.every||(Array.prototype.every=function(t){var e=Object(this),n=de&&{}.toString.call(this)==G?this.split(""):e,r=n.length>>>0,i=arguments[1];if({}.toString.call(t)!=K)throw new TypeError(t+" is not a function");for(var o=0;r>o;o++)if(o in n&&!t.call(i,n[o],o,e))return!1;return!0}),Array.prototype.map||(Array.prototype.map=function(t){var e=Object(this),n=de&&{}.toString.call(this)==G?this.split(""):e,r=n.length>>>0,i=Array(r),o=arguments[1];if({}.toString.call(t)!=K)throw new TypeError(t+" is not a function");for(var s=0;r>s;s++)s in n&&(i[s]=t.call(o,n[s],s,e));return i}),Array.prototype.filter||(Array.prototype.filter=function(t){for(var e,n=[],r=Object(this),i=0,o=r.length>>>0;o>i;i++)e=r[i],i in r&&t.call(arguments[1],e,i,r)&&n.push(e);return n}),Array.isArray||(Array.isArray=function(t){return Object.prototype.toString.call(t)==U}),Array.prototype.indexOf||(Array.prototype.indexOf=function(t){var e=Object(this),n=e.length>>>0;if(0===n)return-1;var r=0;if(arguments.length>1&&(r=Number(arguments[1]),r!==r?r=0:0!==r&&1/0!=r&&r!==-1/0&&(r=(r>0||-1)*Math.floor(Math.abs(r)))),r>=n)return-1;for(var i=r>=0?r:Math.max(n-Math.abs(r),0);n>i;i++)if(i in e&&e[i]===t)return i;return-1});var be=function(t,e){this.id=t,this.value=e};be.prototype.compareTo=function(t){var e=this.value.compareTo(t.value);return 0===e&&(e=this.id-t.id),e};var ve=j.internals.PriorityQueue=function(t){this.items=Array(t),this.length=0},me=ve.prototype;me.isHigherPriority=function(t,e){return 0>this.items[t].compareTo(this.items[e])},me.percolate=function(t){if(!(t>=this.length||0>t)){var e=t-1>>1;if(!(0>e||e===t)&&this.isHigherPriority(t,e)){var n=this.items[t];this.items[t]=this.items[e],this.items[e]=n,this.percolate(e)}}},me.heapify=function(e){if(e===t&&(e=0),!(e>=this.length||0>e)){var n=2*e+1,r=2*e+2,i=e;if(this.length>n&&this.isHigherPriority(n,i)&&(i=n),this.length>r&&this.isHigherPriority(r,i)&&(i=r),i!==e){var o=this.items[e];this.items[e]=this.items[i],this.items[i]=o,this.heapify(i)}}},me.peek=function(){return this.items[0].value},me.removeAt=function(t){this.items[t]=this.items[--this.length],delete this.items[this.length],this.heapify()},me.dequeue=function(){var t=this.peek();return this.removeAt(0),t},me.enqueue=function(t){var e=this.length++;this.items[e]=new be(ve.count++,t),this.percolate(e)},me.remove=function(t){for(var e=0;this.length>e;e++)if(this.items[e].value===t)return this.removeAt(e),!0;return!1},ve.count=0;var ye=j.CompositeDisposable=function(){this.disposables=h(arguments,0),this.isDisposed=!1,this.length=this.disposables.length},we=ye.prototype;we.add=function(t){this.isDisposed?t.dispose():(this.disposables.push(t),this.length++)},we.remove=function(t){var e=!1;if(!this.isDisposed){var n=this.disposables.indexOf(t);-1!==n&&(e=!0,this.disposables.splice(n,1),this.length--,t.dispose())}return e},we.dispose=function(){if(!this.isDisposed){this.isDisposed=!0;var t=this.disposables.slice(0);this.disposables=[],this.length=0;for(var e=0,n=t.length;n>e;e++)t[e].dispose()}},we.clear=function(){var t=this.disposables.slice(0);this.disposables=[],this.length=0;for(var e=0,n=t.length;n>e;e++)t[e].dispose()},we.contains=function(t){return-1!==this.disposables.indexOf(t)},we.toArray=function(){return this.disposables.slice(0)};var ge=j.Disposable=function(t){this.isDisposed=!1,this.action=t||R};ge.prototype.dispose=function(){this.isDisposed||(this.action(),this.isDisposed=!0)};var Ee=ge.create=function(t){return new ge(t)},xe=ge.empty={dispose:R},Ce=function(){function t(t){this.isSingle=t,this.isDisposed=!1,this.current=null}var e=t.prototype;return e.getDisposable=function(){return this.current},e.setDisposable=function(t){if(this.current&&this.isSingle)throw Error("Disposable has already been assigned");var e,n=this.isDisposed;n||(e=this.current,this.current=t),e&&e.dispose(),n&&t&&t.dispose()},e.dispose=function(){var t;this.isDisposed||(this.isDisposed=!0,t=this.current,this.current=null),t&&t.dispose()},t}(),De=j.SingleAssignmentDisposable=function(t){function e(){t.call(this,!0)}return le(e,t),e}(Ce),Se=j.SerialDisposable=function(t){function e(){t.call(this,!1)}return le(e,t),e}(Ce);j.RefCountDisposable=function(){function t(t){this.disposable=t,this.disposable.count++,this.isInnerDisposed=!1}function e(t){this.underlyingDisposable=t,this.isDisposed=!1,this.isPrimaryDisposed=!1,this.count=0}return t.prototype.dispose=function(){this.disposable.isDisposed||this.isInnerDisposed||(this.isInnerDisposed=!0,this.disposable.count--,0===this.disposable.count&&this.disposable.isPrimaryDisposed&&(this.disposable.isDisposed=!0,this.disposable.underlyingDisposable.dispose()))},e.prototype.dispose=function(){this.isDisposed||this.isPrimaryDisposed||(this.isPrimaryDisposed=!0,0===this.count&&(this.isDisposed=!0,this.underlyingDisposable.dispose()))},e.prototype.getDisposable=function(){return this.isDisposed?xe:new t(this)},e}();var Ne=j.internals.ScheduledItem=function(t,e,n,r,i){this.scheduler=t,this.state=e,this.action=n,this.dueTime=r,this.comparer=i||P,this.disposable=new De};Ne.prototype.invoke=function(){this.disposable.setDisposable(this.invokeCore())},Ne.prototype.compareTo=function(t){return this.comparer(this.dueTime,t.dueTime)},Ne.prototype.isCancelled=function(){return this.disposable.isDisposed},Ne.prototype.invokeCore=function(){return this.action(this.scheduler,this.state)};var Ae=j.Scheduler=function(){function t(t,e,n,r){this.now=t,this._schedule=e,this._scheduleRelative=n,this._scheduleAbsolute=r}function e(t,e){var n=e.first,r=e.second,i=new ye,o=function(e){r(e,function(e){var n=!1,r=!1,s=t.scheduleWithState(e,function(t,e){return n?i.remove(s):r=!0,o(e),xe});r||(i.add(s),n=!0)})};return o(n),i}function n(t,e,n){var r=e.first,i=e.second,o=new ye,s=function(e){i(e,function(e,r){var i=!1,u=!1,c=t[n].call(t,e,r,function(t,e){return i?o.remove(c):u=!0,s(e),xe});u||(o.add(c),i=!0)})};return s(r),o}function r(t,e){return e(),xe}var i=t.prototype;return i.schedulePeriodic=function(t,e){return this.schedulePeriodicWithState(null,t,function(){e()})},i.schedulePeriodicWithState=function(t,e,n){var r=t,i=setInterval(function(){r=n(r)},e);return Ee(function(){clearInterval(i)})},i.schedule=function(t){return this._schedule(t,r)},i.scheduleWithState=function(t,e){return this._schedule(t,e)},i.scheduleWithRelative=function(t,e){return this._scheduleRelative(e,t,r)},i.scheduleWithRelativeAndState=function(t,e,n){return this._scheduleRelative(t,e,n)},i.scheduleWithAbsolute=function(t,e){return this._scheduleAbsolute(e,t,r)},i.scheduleWithAbsoluteAndState=function(t,e,n){return this._scheduleAbsolute(t,e,n)},i.scheduleRecursive=function(t){return this.scheduleRecursiveWithState(t,function(t,e){t(function(){e(t)})})},i.scheduleRecursiveWithState=function(t,n){return this.scheduleWithState({first:t,second:n},function(t,n){return e(t,n)})},i.scheduleRecursiveWithRelative=function(t,e){return this.scheduleRecursiveWithRelativeAndState(e,t,function(t,e){t(function(n){e(t,n)})})},i.scheduleRecursiveWithRelativeAndState=function(t,e,r){return this._scheduleRelative({first:t,second:r},e,function(t,e){return n(t,e,"scheduleWithRelativeAndState")})},i.scheduleRecursiveWithAbsolute=function(t,e){return this.scheduleRecursiveWithAbsoluteAndState(e,t,function(t,e){t(function(n){e(t,n)})})},i.scheduleRecursiveWithAbsoluteAndState=function(t,e,r){return this._scheduleAbsolute({first:t,second:r},e,function(t,e){return n(t,e,"scheduleWithAbsoluteAndState")})},t.now=k,t.normalize=function(t){return 0>t&&(t=0),t},t}(),_e=Ae.normalize,Oe=Ae.immediate=function(){function t(t,e){return e(this,t)}function e(t,e,n){for(var r=_e(r);r-this.now()>0;);return n(this,t)}function n(t,e,n){return this.scheduleWithRelativeAndState(t,e-this.now(),n)}return new Ae(k,t,e,n)}(),je=Ae.currentThread=function(){function t(t){for(var e;t.length>0;)if(e=t.dequeue(),!e.isCancelled()){for(;e.dueTime-Ae.now()>0;);e.isCancelled()||e.invoke()}}function e(t,e){return this.scheduleWithRelativeAndState(t,0,e)}function n(e,n,r){var o=this.now()+Ae.normalize(n),s=new Ne(this,e,r,o);if(i)i.enqueue(s);else{i=new ve(4),i.enqueue(s);try{t(i)}catch(u){throw u}finally{i=null}}return s.disposable}function r(t,e,n){return this.scheduleWithRelativeAndState(t,e-this.now(),n)}var i,o=new Ae(k,e,n,r);return o.scheduleRequired=function(){return null===i},o.ensureTrampoline=function(t){return null===i?this.schedule(t):t()},o}();j.internals.SchedulePeriodicRecursive=function(){function t(t,e){e(0,this._period);try{this._state=this._action(this._state)}catch(n){throw this._cancel.dispose(),n}}function e(t,e,n,r){this._scheduler=t,this._state=e,this._period=n,this._action=r}return e.prototype.start=function(){var e=new De;return this._cancel=e,e.setDisposable(this._scheduler.scheduleRecursiveWithRelativeAndState(0,this._period,t.bind(this))),e},e}();var Re,We=R;(function(){function t(){if(!S.postMessage||S.importScripts)return!1;var t=!1,e=S.onmessage;return S.onmessage=function(){t=!0},S.postMessage("","*"),S.onmessage=e,t}function e(t){if("string"==typeof t.data&&t.data.substring(0,o.length)===o){var e=t.data.substring(o.length),n=s[e];n(),delete s[e]}}var n=RegExp("^"+(Y+"").replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/toString| for [^\]]+/g,".*?")+"$"),r="function"==typeof(r=O&&_&&O.setImmediate)&&!n.test(r)&&r,i="function"==typeof(i=O&&_&&O.clearImmediate)&&!n.test(i)&&i;if("undefined"!=typeof process&&"[object process]"==={}.toString.call(process))Re=process.nextTick;else if("function"==typeof r)Re=r,We=i;else if(t()){var o="ms.rx.schedule"+Math.random(),s={},u=0;S.addEventListener?S.addEventListener("message",e,!1):S.attachEvent("onmessage",e,!1),Re=function(t){var e=u++;s[e]=t,S.postMessage(o+e,"*")}}else if(S.MessageChannel){var c=new S.MessageChannel,a={},h=0;c.port1.onmessage=function(t){var e=t.data,n=a[e];n(),delete a[e]},Re=function(t){var e=h++;a[e]=t,c.port2.postMessage(e)}}else"document"in S&&"onreadystatechange"in S.document.createElement("script")?Re=function(t){var e=S.document.createElement("script");e.onreadystatechange=function(){t(),e.onreadystatechange=null,e.parentNode.removeChild(e),e=null},S.document.documentElement.appendChild(e)}:(Re=function(t){return setTimeout(t,0)},We=clearTimeout)})();var ke=Ae.timeout=function(){function t(t,e){var n=this,r=new De,i=Re(function(){r.isDisposed||r.setDisposable(e(n,t))});return new ye(r,Ee(function(){We(i)}))}function e(t,e,n){var r=this,i=Ae.normalize(e);if(0===i)return r.scheduleWithState(t,n);var o=new De,s=setTimeout(function(){o.isDisposed||o.setDisposable(n(r,t))},i);return new ye(o,Ee(function(){clearTimeout(s)}))}function n(t,e,n){return this.scheduleWithRelativeAndState(t,e-this.now(),n)}return new Ae(k,t,e,n)}(),qe=j.Notification=function(){function t(t,e){this.hasValue=null==e?!1:e,this.kind=t}var e=t.prototype;return e.accept=function(t,e,n){return 1===arguments.length&&"object"==typeof t?this._acceptObservable(t):this._accept(t,e,n)},e.toObservable=function(t){var e=this;return t||(t=Oe),new mn(function(n){return t.schedule(function(){e._acceptObservable(n),"N"===e.kind&&n.onCompleted()})})},t}(),Pe=qe.createOnNext=function(){function t(t){return t(this.value)}function e(t){return t.onNext(this.value)}function n(){return"OnNext("+this.value+")"}return function(r){var i=new qe("N",!0);return i.value=r,i._accept=t,i._acceptObservable=e,i.toString=n,i}}(),Te=qe.createOnError=function(){function t(t,e){return e(this.exception)}function e(t){return t.onError(this.exception)}function n(){return"OnError("+this.exception+")"}return function(r){var i=new qe("E");return i.exception=r,i._accept=t,i._acceptObservable=e,i.toString=n,i}}(),Le=qe.createOnCompleted=function(){function t(t,e,n){return n()}function e(t){return t.onCompleted()}function n(){return"OnCompleted()"}return function(){var r=new qe("C");return r._accept=t,r._acceptObservable=e,r.toString=n,r}}(),Ve=j.internals.Enumerator=function(t){this._next=t};Ve.prototype.next=function(){return this._next()},Ve.prototype[M]=function(){return this};var ze=j.internals.Enumerable=function(t){this._iterator=t};ze.prototype[M]=function(){return this._iterator()},ze.prototype.concat=function(){var e=this;return new mn(function(n){var r;try{r=e[M]()}catch(i){return n.onError(),t}var o,s=new Se,u=Oe.scheduleRecursive(function(e){var i;if(!o){try{i=r.next()}catch(u){return n.onError(u),t}if(i.done)return n.onCompleted(),t;var c=i.value;L(c)&&(c=an(c));var a=new De;s.setDisposable(a),a.setDisposable(c.subscribe(n.onNext.bind(n),n.onError.bind(n),function(){e()}))}});return new ye(s,u,Ee(function(){o=!0}))})},ze.prototype.catchException=function(){var e=this;return new mn(function(n){var r;try{r=e[M]()}catch(i){return n.onError(),t}var o,s,u=new Se,c=Oe.scheduleRecursive(function(e){if(!o){var i;try{i=r.next()}catch(c){return n.onError(c),t}if(i.done)return s?n.onError(s):n.onCompleted(),t;var a=i.value;L(a)&&(a=an(a));var h=new De;u.setDisposable(h),h.setDisposable(a.subscribe(n.onNext.bind(n),function(t){s=t,e()},n.onCompleted.bind(n)))}});return new ye(u,c,Ee(function(){o=!0}))})};var Me=ze.repeat=function(t,e){return null==e&&(e=-1),new ze(function(){var n=e;return new Ve(function(){return 0===n?F:(n>0&&n--,{done:!1,value:t})})})},Ie=ze.forEach=function(t,e,n){return e||(e=W),new ze(function(){var r=-1;return new Ve(function(){return++r0&&(e=!this.isAcquired,this.isAcquired=!0),e&&this.disposable.setDisposable(this.scheduler.scheduleRecursive(function(e){var r;if(!(n.queue.length>0))return n.isAcquired=!1,t;r=n.queue.shift();try{r()}catch(i){throw n.queue=[],n.hasFaulted=!0,i}e()}))},n.prototype.dispose=function(){e.prototype.dispose.call(this),this.disposable.dispose()},n}(Qe);Ue.toArray=function(){var t=this;return new mn(function(e){var n=[];return t.subscribe(n.push.bind(n),e.onError.bind(e),function(){e.onNext(n),e.onCompleted()})})},$e.create=$e.createWithDisposable=function(t){return new mn(t)};var Je=$e.defer=function(t){return new mn(function(e){var n;try{n=t()}catch(r){return tn(r).subscribe(e)}return L(n)&&(n=an(n)),n.subscribe(e)})},Ze=$e.empty=function(t){return t||(t=Oe),new mn(function(e){return t.schedule(function(){e.onCompleted()})})},Xe=$e.fromArray=function(t,e){return e||(e=je),new mn(function(n){var r=0,i=t.length;return e.scheduleRecursive(function(e){i>r?(n.onNext(t[r++]),e()):n.onCompleted()})})};$e.fromIterable=function(e,n){return n||(n=je),new mn(function(r){var i;try{i=e[M]()}catch(o){return r.onError(o),t}return n.scheduleRecursive(function(e){var n;try{n=i.next()}catch(o){return r.onError(o),t}n.done?r.onCompleted():(r.onNext(n.value),e())})})},$e.generate=function(e,n,r,i,o){return o||(o=je),new mn(function(s){var u=!0,c=e;return o.scheduleRecursive(function(e){var o,a;try{u?u=!1:c=r(c),o=n(c),o&&(a=i(c))}catch(h){return s.onError(h),t}o?(s.onNext(a),e()):s.onCompleted()})})};var Ge=$e.never=function(){return new mn(function(){return xe})};$e.of=function(){for(var t=arguments.length,e=Array(t),n=0;t>n;n++)e[n]=arguments[n];return Xe(e)},$e.ofWithScheduler=function(t){for(var e=arguments.length-1,n=Array(e),r=0;e>r;r++)n[r]=arguments[r+1];return Xe(n,t)},$e.range=function(t,e,n){return n||(n=je),new mn(function(r){return n.scheduleRecursiveWithState(0,function(n,i){e>n?(r.onNext(t+n),i(n+1)):r.onCompleted()})})},$e.repeat=function(t,e,n){return n||(n=je),null==e&&(e=-1),Ye(t,n).repeat(e)};var Ye=$e["return"]=$e.returnValue=$e.just=function(t,e){return e||(e=Oe),new mn(function(n){return e.schedule(function(){n.onNext(t),n.onCompleted()})})},tn=$e["throw"]=$e.throwException=function(t,e){return e||(e=Oe),new mn(function(n){return e.schedule(function(){n.onError(t)})})};Ue["catch"]=Ue.catchException=function(t){return"function"==typeof t?f(this,t):en([this,t])};var en=$e.catchException=$e["catch"]=function(){var t=h(arguments,0);return Ie(t).catchException()};Ue.combineLatest=function(){var t=he.call(arguments);return Array.isArray(t[0])?t[0].unshift(this):t.unshift(this),nn.apply(this,t)};var nn=$e.combineLatest=function(){var e=he.call(arguments),n=e.pop();return Array.isArray(e[0])&&(e=e[0]),new mn(function(r){function i(e){var i;if(c[e]=!0,a||(a=c.every(W))){try{i=n.apply(null,f)}catch(o){return r.onError(o),t}r.onNext(i)}else h.filter(function(t,n){return n!==e}).every(W)&&r.onCompleted()}function o(t){h[t]=!0,h.every(W)&&r.onCompleted()}for(var s=function(){return!1},u=e.length,c=l(u,s),a=!1,h=l(u,s),f=Array(u),p=Array(u),d=0;u>d;d++)(function(t){var n=e[t],s=new De;L(n)&&(n=an(n)),s.setDisposable(n.subscribe(function(e){f[t]=e,i(t)},r.onError.bind(r),function(){o(t)})),p[t]=s})(d);return new ye(p)})};Ue.concat=function(){var t=he.call(arguments,0);return t.unshift(this),rn.apply(this,t)};var rn=$e.concat=function(){var t=h(arguments,0);return Ie(t).concat()};Ue.concatObservable=Ue.concatAll=function(){return this.merge(1)},Ue.merge=function(t){if("number"!=typeof t)return on(this,t);var e=this;return new mn(function(n){var r=0,i=new ye,o=!1,s=[],u=function(t){var e=new De;i.add(e),L(t)&&(t=an(t)),e.setDisposable(t.subscribe(n.onNext.bind(n),n.onError.bind(n),function(){var t;i.remove(e),s.length>0?(t=s.shift(),u(t)):(r--,o&&0===r&&n.onCompleted())}))};return i.add(e.subscribe(function(e){t>r?(r++,u(e)):s.push(e)},n.onError.bind(n),function(){o=!0,0===r&&n.onCompleted()})),i})};var on=$e.merge=function(){var t,e;return arguments[0]?arguments[0].now?(t=arguments[0],e=he.call(arguments,1)):(t=Oe,e=he.call(arguments,0)):(t=Oe,e=he.call(arguments,1)),Array.isArray(e[0])&&(e=e[0]),Xe(e,t).mergeObservable()};Ue.mergeObservable=Ue.mergeAll=function(){var t=this;return new mn(function(e){var n=new ye,r=!1,i=new De;return n.add(i),i.setDisposable(t.subscribe(function(t){var i=new De;n.add(i),L(t)&&(t=an(t)),i.setDisposable(t.subscribe(function(t){e.onNext(t)},e.onError.bind(e),function(){n.remove(i),r&&1===n.length&&e.onCompleted()}))},e.onError.bind(e),function(){r=!0,1===n.length&&e.onCompleted()})),n})},Ue.skipUntil=function(t){var e=this;return new mn(function(n){var r=!1,i=new ye(e.subscribe(function(t){r&&n.onNext(t)},n.onError.bind(n),function(){r&&n.onCompleted()}));L(t)&&(t=an(t));var o=new De;return i.add(o),o.setDisposable(t.subscribe(function(){r=!0,o.dispose()},n.onError.bind(n),function(){o.dispose()})),i})},Ue["switch"]=Ue.switchLatest=function(){var t=this;return new mn(function(e){var n=!1,r=new Se,i=!1,o=0,s=t.subscribe(function(t){var s=new De,u=++o;n=!0,r.setDisposable(s),L(t)&&(t=an(t)),s.setDisposable(t.subscribe(function(t){o===u&&e.onNext(t)},function(t){o===u&&e.onError(t)},function(){o===u&&(n=!1,i&&e.onCompleted())}))},e.onError.bind(e),function(){i=!0,n||e.onCompleted()});return new ye(s,r)})},Ue.takeUntil=function(t){var e=this;return new mn(function(n){return L(t)&&(t=an(t)),new ye(e.subscribe(n),t.subscribe(n.onCompleted.bind(n),n.onError.bind(n),R))})},Ue.zip=function(){if(Array.isArray(arguments[0]))return p.apply(this,arguments);var e=this,n=he.call(arguments),r=n.pop();return n.unshift(e),new mn(function(i){function o(n){var o,s;if(c.every(function(t){return t.length>0})){try{s=c.map(function(t){return t.shift()}),o=r.apply(e,s)}catch(u){return i.onError(u),t}i.onNext(o)}else a.filter(function(t,e){return e!==n}).every(W)&&i.onCompleted()}function s(t){a[t]=!0,a.every(function(t){return t})&&i.onCompleted()}for(var u=n.length,c=l(u,function(){return[]}),a=l(u,function(){return!1}),h=Array(u),f=0;u>f;f++)(function(t){var e=n[t],r=new De;L(e)&&(e=an(e)),r.setDisposable(e.subscribe(function(e){c[t].push(e),o(t)},i.onError.bind(i),function(){s(t)})),h[t]=r})(f);return new ye(h)})},$e.zip=function(){var t=he.call(arguments,0),e=t.shift();return e.zip.apply(e,t)},$e.zipArray=function(){var e=h(arguments,0);return new mn(function(n){function r(e){if(s.every(function(t){return t.length>0})){var r=s.map(function(t){return t.shift()});n.onNext(r)}else if(u.filter(function(t,n){return n!==e}).every(W))return n.onCompleted(),t}function i(e){return u[e]=!0,u.every(W)?(n.onCompleted(),t):t}for(var o=e.length,s=l(o,function(){return[]}),u=l(o,function(){return!1}),c=Array(o),a=0;o>a;a++)(function(t){c[t]=new De,c[t].setDisposable(e[t].subscribe(function(e){s[t].push(e),r(t)},n.onError.bind(n),function(){i(t)}))})(a);var h=new ye(c);return h.add(Ee(function(){for(var t=0,e=s.length;e>t;t++)s[t]=[]})),h})},Ue.asObservable=function(){var t=this;return new mn(function(e){return t.subscribe(e)})},Ue.dematerialize=function(){var t=this;return new mn(function(e){return t.subscribe(function(t){return t.accept(e)},e.onError.bind(e),e.onCompleted.bind(e))})},Ue.distinctUntilChanged=function(e,n){var r=this;return e||(e=W),n||(n=q),new mn(function(i){var o,s=!1;return r.subscribe(function(r){var u,c=!1;try{u=e(r)}catch(a){return i.onError(a),t}if(s)try{c=n(o,u)}catch(a){return i.onError(a),t}s&&c||(s=!0,o=u,i.onNext(r))},i.onError.bind(i),i.onCompleted.bind(i))})},Ue["do"]=Ue.doAction=function(t,e,n){var r,i=this;return"function"==typeof t?r=t:(r=t.onNext.bind(t),e=t.onError.bind(t),n=t.onCompleted.bind(t)),new mn(function(t){return i.subscribe(function(e){try{r(e)}catch(n){t.onError(n)}t.onNext(e)},function(n){if(e){try{e(n)}catch(r){t.onError(r)}t.onError(n)}else t.onError(n)},function(){if(n){try{n()}catch(e){t.onError(e)}t.onCompleted()}else t.onCompleted()})})},Ue["finally"]=Ue.finallyAction=function(t){var e=this;return new mn(function(n){var r;try{r=e.subscribe(n)}catch(i){throw t(),i}return Ee(function(){try{r.dispose()}catch(e){throw e}finally{t()}})})},Ue.ignoreElements=function(){var t=this;return new mn(function(e){return t.subscribe(R,e.onError.bind(e),e.onCompleted.bind(e)) +})},Ue.materialize=function(){var t=this;return new mn(function(e){return t.subscribe(function(t){e.onNext(Pe(t))},function(t){e.onNext(Te(t)),e.onCompleted()},function(){e.onNext(Le()),e.onCompleted()})})},Ue.repeat=function(t){return Me(this,t).concat()},Ue.retry=function(t){return Me(this,t).catchException()},Ue.scan=function(){var e,n,r=!1,i=this;return 2===arguments.length?(r=!0,e=arguments[0],n=arguments[1]):n=arguments[0],new mn(function(o){var s,u,c;return i.subscribe(function(i){try{c||(c=!0),s?u=n(u,i):(u=r?n(e,i):i,s=!0)}catch(a){return o.onError(a),t}o.onNext(u)},o.onError.bind(o),function(){!c&&r&&o.onNext(e),o.onCompleted()})})},Ue.skipLast=function(t){var e=this;return new mn(function(n){var r=[];return e.subscribe(function(e){r.push(e),r.length>t&&n.onNext(r.shift())},n.onError.bind(n),n.onCompleted.bind(n))})},Ue.startWith=function(){var t,e,n=0;return arguments.length&&"now"in Object(arguments[0])?(e=arguments[0],n=1):e=Oe,t=he.call(arguments,n),Ie([Xe(t,e),this]).concat()},Ue.takeLast=function(t,e){return this.takeLastBuffer(t).selectMany(function(t){return Xe(t,e)})},Ue.takeLastBuffer=function(t){var e=this;return new mn(function(n){var r=[];return e.subscribe(function(e){r.push(e),r.length>t&&r.shift()},n.onError.bind(n),function(){n.onNext(r),n.onCompleted()})})},Ue.selectConcat=Ue.concatMap=function(t,e){return e?this.concatMap(function(n,r){var i=t(n,r),o=L(i)?an(i):i;return o.map(function(t){return e(n,t,r)})}):"function"==typeof t?d.call(this,t):d.call(this,function(){return t})},Ue.select=Ue.map=function(e,n){var r=this;return new mn(function(i){var o=0;return r.subscribe(function(s){var u;try{u=e.call(n,s,o++,r)}catch(c){return i.onError(c),t}i.onNext(u)},i.onError.bind(i),i.onCompleted.bind(i))})},Ue.pluck=function(t){return this.select(function(e){return e[t]})},Ue.selectMany=Ue.flatMap=function(t,e){return e?this.selectMany(function(n,r){var i=t(n,r),o=L(i)?an(i):i;return o.select(function(t){return e(n,t,r)})}):"function"==typeof t?b.call(this,t):b.call(this,function(){return t})},Ue.selectSwitch=Ue.flatMapLatest=Ue.switchMap=function(t,e){return this.select(t,e).switchLatest()},Ue.skip=function(t){if(0>t)throw Error(V);var e=this;return new mn(function(n){var r=t;return e.subscribe(function(t){0>=r?n.onNext(t):r--},n.onError.bind(n),n.onCompleted.bind(n))})},Ue.skipWhile=function(e,n){var r=this;return new mn(function(i){var o=0,s=!1;return r.subscribe(function(u){if(!s)try{s=!e.call(n,u,o++,r)}catch(c){return i.onError(c),t}s&&i.onNext(u)},i.onError.bind(i),i.onCompleted.bind(i))})},Ue.take=function(t,e){if(0>t)throw Error(V);if(0===t)return Ze(e);var n=this;return new mn(function(e){var r=t;return n.subscribe(function(t){r>0&&(r--,e.onNext(t),0===r&&e.onCompleted())},e.onError.bind(e),e.onCompleted.bind(e))})},Ue.takeWhile=function(e,n){var r=this;return new mn(function(i){var o=0,s=!0;return r.subscribe(function(u){if(s){try{s=e.call(n,u,o++,r)}catch(c){return i.onError(c),t}s?i.onNext(u):i.onCompleted()}},i.onError.bind(i),i.onCompleted.bind(i))})},Ue.where=Ue.filter=function(e,n){var r=this;return new mn(function(i){var o=0;return r.subscribe(function(s){var u;try{u=e.call(n,s,o++,r)}catch(c){return i.onError(c),t}u&&i.onNext(s)},i.onError.bind(i),i.onCompleted.bind(i))})},$e.fromCallback=function(e,n,r,i){return n||(n=Oe),function(){var o=he.call(arguments,0);return new mn(function(s){return n.schedule(function(){function n(e){var n=e;if(i)try{n=i(arguments)}catch(r){return s.onError(r),t}else 1===n.length&&(n=n[0]);s.onNext(n),s.onCompleted()}o.push(n),e.apply(r,o)})})}},$e.fromNodeCallback=function(e,n,r,i){return n||(n=Oe),function(){var o=he.call(arguments,0);return new mn(function(s){return n.schedule(function(){function n(e){if(e)return s.onError(e),t;var n=he.call(arguments,1);if(i)try{n=i(n)}catch(r){return s.onError(r),t}else 1===n.length&&(n=n[0]);s.onNext(n),s.onCompleted()}o.push(n),e.apply(r,o)})})}};var sn=S.angular&&angular.element?angular.element:S.jQuery?S.jQuery:S.Zepto?S.Zepto:null,un=!!S.Ember&&"function"==typeof S.Ember.addListener;$e.fromEvent=function(e,n,r){if(un)return cn(function(t){Ember.addListener(e,n,t)},function(t){Ember.removeListener(e,n,t)},r);if(sn){var i=sn(e);return cn(function(t){i.on(n,t)},function(t){i.off(n,t)},r)}return new mn(function(i){return y(e,n,function(e){var n=e;if(r)try{n=r(arguments)}catch(o){return i.onError(o),t}i.onNext(n)})}).publish().refCount()};var cn=$e.fromEventPattern=function(e,n,r){return new mn(function(i){function o(e){var n=e;if(r)try{n=r(arguments)}catch(o){return i.onError(o),t}i.onNext(n)}var s=e(o);return Ee(function(){n&&n(o,s)})}).publish().refCount()},an=$e.fromPromise=function(t){return new mn(function(e){return t.then(function(t){e.onNext(t),e.onCompleted()},function(t){e.onError(t)}),function(){t&&t.abort&&t.abort()}})};Ue.toPromise=function(t){if(t||(t=j.config.Promise),!t)throw Error("Promise type not provided nor in Rx.config.Promise");var e=this;return new t(function(t,n){var r,i=!1;e.subscribe(function(t){r=t,i=!0},function(t){n(t)},function(){i&&t(r)})})},$e.startAsync=function(t){var e;try{e=t()}catch(n){return tn(n)}return an(e)},Ue.multicast=function(t,e){var n=this;return"function"==typeof t?new mn(function(r){var i=n.multicast(t());return new ye(e(i).subscribe(r),i.connect())}):new hn(n,t)},Ue.publish=function(t){return t?this.multicast(function(){return new gn},t):this.multicast(new gn)},Ue.share=function(){return this.publish(null).refCount()},Ue.publishLast=function(t){return t?this.multicast(function(){return new En},t):this.multicast(new En)},Ue.publishValue=function(t,e){return 2===arguments.length?this.multicast(function(){return new Cn(e)},t):this.multicast(new Cn(t))},Ue.shareValue=function(t){return this.publishValue(t).refCount()},Ue.replay=function(t,e,n,r){return t?this.multicast(function(){return new Dn(e,n,r)},t):this.multicast(new Dn(e,n,r))},Ue.shareReplay=function(t,e,n){return this.replay(null,t,e,n).refCount()};var hn=j.ConnectableObservable=function(t){function e(e,n){function r(t){return i.subject.subscribe(t)}var i={subject:n,source:e.asObservable(),hasSubscription:!1,subscription:null};this.connect=function(){return i.hasSubscription||(i.hasSubscription=!0,i.subscription=new ye(i.source.subscribe(i.subject),Ee(function(){i.hasSubscription=!1}))),i.subscription},t.call(this,r)}return le(e,t),e.prototype.connect=function(){return this.connect()},e.prototype.refCount=function(){var t=null,e=0,n=this;return new mn(function(r){var i,o;return e++,i=1===e,o=n.subscribe(r),i&&(t=n.connect()),Ee(function(){o.dispose(),e--,0===e&&t.dispose()})})},e}($e),ln=$e.interval=function(t,e){return e||(e=ke),g(t,t,e)},fn=$e.timer=function(e,n,r){var i;return r||(r=ke),"number"==typeof n?i=n:"object"==typeof n&&"now"in n&&(r=n),i===t?w(e,r):g(e,i,r)};Ue.delay=function(t,e){e||(e=ke);var n=this;return new mn(function(r){var i,o=!1,s=new Se,u=null,c=[],a=!1;return i=n.materialize().timestamp(e).subscribe(function(n){var i,h;"E"===n.value.kind?(c=[],c.push(n),u=n.value.exception,h=!a):(c.push({value:n.value,timestamp:n.timestamp+t}),h=!o,o=!0),h&&(null!==u?r.onError(u):(i=new De,s.setDisposable(i),i.setDisposable(e.scheduleRecursiveWithRelative(t,function(t){var n,i,s,h;if(null===u){a=!0;do s=null,c.length>0&&0>=c[0].timestamp-e.now()&&(s=c.shift().value),null!==s&&s.accept(r);while(null!==s);h=!1,i=0,c.length>0?(h=!0,i=Math.max(0,c[0].timestamp-e.now())):o=!1,n=u,a=!1,null!==n?r.onError(n):h&&t(i)}}))))}),new ye(i,s)})},Ue.throttle=function(t,e){return e||(e=ke),this.throttleWithSelector(function(){return fn(t,e)})},Ue.timeInterval=function(t){var e=this;return t||(t=ke),Je(function(){var n=t.now();return e.select(function(e){var r=t.now(),i=r-n;return n=r,{value:e,interval:i}})})},Ue.timestamp=function(t){return t||(t=ke),this.select(function(e){return{value:e,timestamp:t.now()}})},Ue.sample=function(t,e){return e||(e=ke),"number"==typeof t?x(this,ln(t,e)):x(this,t)},Ue.timeout=function(t,e,n){e||(e=tn(Error("Timeout"))),n||(n=ke);var r=this,i=t instanceof Date?"scheduleWithAbsolute":"scheduleWithRelative";return new mn(function(o){var s=0,u=new De,c=new Se,a=!1,h=new Se;c.setDisposable(u);var l=function(){var r=s;h.setDisposable(n[i](t,function(){s===r&&(L(e)&&(e=an(e)),c.setDisposable(e.subscribe(o)))}))};return l(),u.setDisposable(r.subscribe(function(t){a||(s++,o.onNext(t),l())},function(t){a||(s++,o.onError(t))},function(){a||(s++,o.onCompleted())})),new ye(c,h)})},$e.generateWithRelativeTime=function(e,n,r,i,o,s){return s||(s=ke),new mn(function(u){var c,a,h=!0,l=!1,f=e;return s.scheduleRecursiveWithRelative(0,function(e){l&&u.onNext(c);try{h?h=!1:f=r(f),l=n(f),l&&(c=i(f),a=o(f))}catch(s){return u.onError(s),t}l?e(a):u.onCompleted()})})},Ue.delaySubscription=function(t,e){return e||(e=ke),this.delayWithSelector(fn(t,e),function(){return Ze()})},Ue.delayWithSelector=function(e,n){var r,i,o=this;return"function"==typeof e?i=e:(r=e,i=n),new mn(function(e){var n=new ye,s=!1,u=function(){s&&0===n.length&&e.onCompleted()},c=new Se,a=function(){c.setDisposable(o.subscribe(function(r){var o;try{o=i(r)}catch(s){return e.onError(s),t}var c=new De;n.add(c),c.setDisposable(o.subscribe(function(){e.onNext(r),n.remove(c),u()},e.onError.bind(e),function(){e.onNext(r),n.remove(c),u()}))},e.onError.bind(e),function(){s=!0,c.dispose(),u()}))};return r?c.setDisposable(r.subscribe(function(){a()},e.onError.bind(e),function(){a()})):a(),new ye(c,n)})},Ue.timeoutWithSelector=function(e,n,r){if(1===arguments.length){n=e;var e=Ge()}r||(r=tn(Error("Timeout")));var i=this;return new mn(function(o){var s=new Se,u=new Se,c=new De;s.setDisposable(c);var a=0,h=!1,l=function(t){var e=a,n=function(){return a===e},i=new De;u.setDisposable(i),i.setDisposable(t.subscribe(function(){n()&&s.setDisposable(r.subscribe(o)),i.dispose()},function(t){n()&&o.onError(t)},function(){n()&&s.setDisposable(r.subscribe(o))}))};l(e);var f=function(){var t=!h;return t&&a++,t};return c.setDisposable(i.subscribe(function(e){if(f()){o.onNext(e);var r;try{r=n(e)}catch(i){return o.onError(i),t}l(r)}},function(t){f()&&o.onError(t)},function(){f()&&o.onCompleted()})),new ye(s,u)})},Ue.throttleWithSelector=function(e){var n=this;return new mn(function(r){var i,o=!1,s=new Se,u=0,c=n.subscribe(function(n){var c;try{c=e(n)}catch(a){return r.onError(a),t}o=!0,i=n,u++;var h=u,l=new De;s.setDisposable(l),l.setDisposable(c.subscribe(function(){o&&u===h&&r.onNext(i),o=!1,l.dispose()},r.onError.bind(r),function(){o&&u===h&&r.onNext(i),o=!1,l.dispose()}))},function(t){s.dispose(),r.onError(t),o=!1,u++},function(){s.dispose(),o&&r.onNext(i),r.onCompleted(),o=!1,u++});return new ye(c,s)})},Ue.skipLastWithTime=function(t,e){e||(e=ke);var n=this;return new mn(function(r){var i=[];return n.subscribe(function(n){var o=e.now();for(i.push({interval:o,value:n});i.length>0&&o-i[0].interval>=t;)r.onNext(i.shift().value)},r.onError.bind(r),function(){for(var n=e.now();i.length>0&&n-i[0].interval>=t;)r.onNext(i.shift().value);r.onCompleted()})})},Ue.takeLastWithTime=function(t,e,n){return this.takeLastBufferWithTime(t,e).selectMany(function(t){return Xe(t,n)})},Ue.takeLastBufferWithTime=function(t,e){var n=this;return e||(e=ke),new mn(function(r){var i=[];return n.subscribe(function(n){var r=e.now();for(i.push({interval:r,value:n});i.length>0&&r-i[0].interval>=t;)i.shift()},r.onError.bind(r),function(){for(var n=e.now(),o=[];i.length>0;){var s=i.shift();t>=n-s.interval&&o.push(s.value)}r.onNext(o),r.onCompleted()})})},Ue.takeWithTime=function(t,e){var n=this;return e||(e=ke),new mn(function(r){var i=e.scheduleWithRelative(t,function(){r.onCompleted()});return new ye(i,n.subscribe(r))})},Ue.skipWithTime=function(t,e){var n=this;return e||(e=ke),new mn(function(r){var i=!1,o=e.scheduleWithRelative(t,function(){i=!0}),s=n.subscribe(function(t){i&&r.onNext(t)},r.onError.bind(r),r.onCompleted.bind(r));return new ye(o,s)})},Ue.skipUntilWithTime=function(t,e){e||(e=ke);var n=this,r=t instanceof Date?"scheduleWithAbsolute":"scheduleWithRelative";return new mn(function(i){var o=!1;return new ye(e[r](t,function(){o=!0}),n.subscribe(function(t){o&&i.onNext(t)},i.onError.bind(i),i.onCompleted.bind(i)))})},Ue.takeUntilWithTime=function(t,e){e||(e=ke);var n=this,r=t instanceof Date?"scheduleWithAbsolute":"scheduleWithRelative";return new mn(function(i){return new ye(e[r](t,function(){i.onCompleted()}),n.subscribe(i))})};var pn=function(t){function e(t){var e=this.source.publish(),n=e.subscribe(t),r=xe,i=this.subject.distinctUntilChanged().subscribe(function(t){t?r=e.connect():(r.dispose(),r=xe)});return new ye(n,r,i)}function n(n,r){this.source=n,this.subject=r||new gn,this.isPaused=!0,t.call(this,e)}return le(n,t),n.prototype.pause=function(){this.isPaused!==!0&&(this.isPaused=!0,this.subject.onNext(!1))},n.prototype.resume=function(){this.isPaused!==!1&&(this.isPaused=!1,this.subject.onNext(!0))},n}($e);Ue.pausable=function(t){return new pn(this,t)};var dn=function(t){function e(t){var e=[],n=!0,r=C(this.source,this.subject.distinctUntilChanged(),function(t,e){return{data:t,shouldFire:e}}).subscribe(function(r){if(r.shouldFire&&n&&t.onNext(r.data),r.shouldFire&&!n){for(;e.length>0;)t.onNext(e.shift());n=!0}else r.shouldFire||n?!r.shouldFire&&n&&(n=!1):e.push(r.data)},function(n){for(;e.length>0;)t.onNext(e.shift());t.onError(n)},function(){for(;e.length>0;)t.onNext(e.shift());t.onCompleted()});return this.subject.onNext(!1),r}function n(n,r){this.source=n,this.subject=r||new gn,this.isPaused=!0,t.call(this,e)}return le(n,t),n.prototype.pause=function(){this.isPaused!==!0&&(this.isPaused=!0,this.subject.onNext(!1))},n.prototype.resume=function(){this.isPaused!==!1&&(this.isPaused=!1,this.subject.onNext(!0))},n}($e);Ue.pausableBuffered=function(t){return new dn(this,t)},Ue.controlled=function(t){return null==t&&(t=!0),new bn(this,t)};var bn=function(t){function e(t){return this.source.subscribe(t)}function n(n,r){t.call(this,e),this.subject=new vn(r),this.source=n.multicast(this.subject).refCount()}return le(n,t),n.prototype.request=function(t){return null==t&&(t=-1),this.subject.request(t)},n}($e),vn=j.ControlledSubject=function(t){function n(t){return this.subject.subscribe(t)}function r(e){null==e&&(e=!0),t.call(this,n),this.subject=new gn,this.enableQueue=e,this.queue=e?[]:null,this.requestedCount=0,this.requestedDisposable=xe,this.error=null,this.hasFailed=!1,this.hasCompleted=!1,this.controlledDisposable=xe}return le(r,t),fe(r.prototype,Fe,{onCompleted:function(){e.call(this),this.hasCompleted=!0,this.enableQueue&&0!==this.queue.length||this.subject.onCompleted()},onError:function(t){e.call(this),this.hasFailed=!0,this.error=t,this.enableQueue&&0!==this.queue.length||this.subject.onError(t)},onNext:function(t){e.call(this);var n=!1;0===this.requestedCount?this.enableQueue&&this.queue.push(t):(-1!==this.requestedCount&&0===this.requestedCount--&&this.disposeCurrentRequest(),n=!0),n&&this.subject.onNext(t)},_processRequest:function(t){if(this.enableQueue){for(;this.queue.length>=t&&t>0;)this.subject.onNext(this.queue.shift()),t--;return 0!==this.queue.length?{numberOfItems:t,returnValue:!0}:{numberOfItems:t,returnValue:!1}}return this.hasFailed?(this.subject.onError(this.error),this.controlledDisposable.dispose(),this.controlledDisposable=xe):this.hasCompleted&&(this.subject.onCompleted(),this.controlledDisposable.dispose(),this.controlledDisposable=xe),{numberOfItems:t,returnValue:!1}},request:function(t){e.call(this),this.disposeCurrentRequest();var n=this,r=this._processRequest(t);return t=r.numberOfItems,r.returnValue?xe:(this.requestedCount=t,this.requestedDisposable=Ee(function(){n.requestedCount=0}),this.requestedDisposable)},disposeCurrentRequest:function(){this.requestedDisposable.dispose(),this.requestedDisposable=xe},dispose:function(){this.isDisposed=!0,this.error=null,this.subject.dispose(),this.requestedDisposable.dispose()}}),r}($e);Ue.pairwise=function(){var t=this;return new mn(function(e){var n,r=!1;return t.subscribe(function(t){r?e.onNext([n,t]):r=!0,n=t},e.onError.bind(e),e.onCompleted.bind(e))})},Ue.partition=function(t,e){var n=this.publish().refCount();return[n.filter(t,e),n.filter(function(n,r,i){return!t.call(e,n,r,i)})]},Ue.exclusive=function(){var t=this;return new mn(function(e){var n=!1,r=!1,i=new De,o=new ye;return o.add(i),i.setDisposable(t.subscribe(function(t){if(!n){n=!0,L(t)&&(t=an(t));var i=new De;o.add(i),i.setDisposable(t.subscribe(e.onNext.bind(e),e.onError.bind(e),function(){o.remove(i),n=!1,r&&1===o.length&&e.onCompleted()}))}},e.onError.bind(e),function(){r=!0,n||1!==o.length||e.onCompleted()})),o})},Ue.exclusiveMap=function(e,n){var r=this;return new mn(function(i){var o=0,s=!1,u=!0,c=new De,a=new ye;return a.add(c),c.setDisposable(r.subscribe(function(r){s||(s=!0,innerSubscription=new De,a.add(innerSubscription),L(r)&&(r=an(r)),innerSubscription.setDisposable(r.subscribe(function(s){var u;try{u=e.call(n,s,o++,r)}catch(c){return i.onError(c),t}i.onNext(u)},i.onError.bind(i),function(){a.remove(innerSubscription),s=!1,u&&1===a.length&&i.onCompleted()})))},i.onError.bind(i),function(){u=!0,1!==a.length||s||i.onCompleted()})),a})};var mn=j.AnonymousObservable=function(e){function n(e){return e===t?e=xe:"function"==typeof e&&(e=Ee(e)),e}function r(i){function o(t){var e=function(){try{r.setDisposable(n(i(r)))}catch(t){if(!r.fail(t))throw t}},r=new yn(t);return je.scheduleRequired()?je.schedule(e):e(),r}return this instanceof r?(e.call(this,o),t):new r(i)}return le(r,e),r}($e),yn=function(t){function e(e){t.call(this),this.observer=e,this.m=new De}le(e,t);var n=e.prototype;return n.next=function(t){var e=!1;try{this.observer.onNext(t),e=!0}catch(n){throw n}finally{e||this.dispose()}},n.error=function(t){try{this.observer.onError(t)}catch(e){throw e}finally{this.dispose()}},n.completed=function(){try{this.observer.onCompleted()}catch(t){throw t}finally{this.dispose()}},n.setDisposable=function(t){this.m.setDisposable(t)},n.getDisposable=function(){return this.m.getDisposable()},n.disposable=function(t){return arguments.length?this.getDisposable():setDisposable(t)},n.dispose=function(){t.prototype.dispose.call(this),this.m.dispose()},e}(Qe),wn=function(t,e){this.subject=t,this.observer=e};wn.prototype.dispose=function(){if(!this.subject.isDisposed&&null!==this.observer){var t=this.subject.observers.indexOf(this.observer);this.subject.observers.splice(t,1),this.observer=null}};var gn=j.Subject=function(t){function n(t){return e.call(this),this.isStopped?this.exception?(t.onError(this.exception),xe):(t.onCompleted(),xe):(this.observers.push(t),new wn(this,t))}function r(){t.call(this,n),this.isDisposed=!1,this.isStopped=!1,this.observers=[]}return le(r,t),fe(r.prototype,Fe,{hasObservers:function(){return this.observers.length>0},onCompleted:function(){if(e.call(this),!this.isStopped){var t=this.observers.slice(0);this.isStopped=!0;for(var n=0,r=t.length;r>n;n++)t[n].onCompleted();this.observers=[]}},onError:function(t){if(e.call(this),!this.isStopped){var n=this.observers.slice(0);this.isStopped=!0,this.exception=t;for(var r=0,i=n.length;i>r;r++)n[r].onError(t);this.observers=[]}},onNext:function(t){if(e.call(this),!this.isStopped)for(var n=this.observers.slice(0),r=0,i=n.length;i>r;r++)n[r].onNext(t)},dispose:function(){this.isDisposed=!0,this.observers=null}}),r.create=function(t,e){return new xn(t,e)},r}($e),En=j.AsyncSubject=function(t){function n(t){if(e.call(this),!this.isStopped)return this.observers.push(t),new wn(this,t);var n=this.exception,r=this.hasValue,i=this.value;return n?t.onError(n):r?(t.onNext(i),t.onCompleted()):t.onCompleted(),xe}function r(){t.call(this,n),this.isDisposed=!1,this.isStopped=!1,this.value=null,this.hasValue=!1,this.observers=[],this.exception=null}return le(r,t),fe(r.prototype,Fe,{hasObservers:function(){return e.call(this),this.observers.length>0},onCompleted:function(){var t,n,r;if(e.call(this),!this.isStopped){this.isStopped=!0;var i=this.observers.slice(0),o=this.value,s=this.hasValue;if(s)for(n=0,r=i.length;r>n;n++)t=i[n],t.onNext(o),t.onCompleted();else for(n=0,r=i.length;r>n;n++)i[n].onCompleted();this.observers=[]}},onError:function(t){if(e.call(this),!this.isStopped){var n=this.observers.slice(0);this.isStopped=!0,this.exception=t;for(var r=0,i=n.length;i>r;r++)n[r].onError(t);this.observers=[]}},onNext:function(t){e.call(this),this.isStopped||(this.value=t,this.hasValue=!0)},dispose:function(){this.isDisposed=!0,this.observers=null,this.exception=null,this.value=null}}),r}($e),xn=function(t){function e(t){return this.observable.subscribe(t)}function n(n,r){t.call(this,e),this.observer=n,this.observable=r}return le(n,t),fe(n.prototype,Fe,{onCompleted:function(){this.observer.onCompleted()},onError:function(t){this.observer.onError(t)},onNext:function(t){this.observer.onNext(t)}}),n}($e),Cn=j.BehaviorSubject=function(t){function n(t){if(e.call(this),!this.isStopped)return this.observers.push(t),t.onNext(this.value),new wn(this,t);var n=this.exception;return n?t.onError(n):t.onCompleted(),xe}function r(e){t.call(this,n),this.value=e,this.observers=[],this.isDisposed=!1,this.isStopped=!1,this.exception=null}return le(r,t),fe(r.prototype,Fe,{hasObservers:function(){return this.observers.length>0},onCompleted:function(){if(e.call(this),!this.isStopped){var t=this.observers.slice(0);this.isStopped=!0;for(var n=0,r=t.length;r>n;n++)t[n].onCompleted();this.observers=[]}},onError:function(t){if(e.call(this),!this.isStopped){var n=this.observers.slice(0);this.isStopped=!0,this.exception=t;for(var r=0,i=n.length;i>r;r++)n[r].onError(t);this.observers=[]}},onNext:function(t){if(e.call(this),!this.isStopped){this.value=t;for(var n=this.observers.slice(0),r=0,i=n.length;i>r;r++)n[r].onNext(t)}},dispose:function(){this.isDisposed=!0,this.observers=null,this.value=null,this.exception=null}}),r}($e),Dn=j.ReplaySubject=function(t){function n(t,e){this.subject=t,this.observer=e}function r(t){var r=new Ke(this.scheduler,t),i=new n(this,r);e.call(this),this._trim(this.scheduler.now()),this.observers.push(r);for(var o=this.q.length,s=0,u=this.q.length;u>s;s++)r.onNext(this.q[s].value);return this.hasError?(o++,r.onError(this.error)):this.isStopped&&(o++,r.onCompleted()),r.ensureActive(o),i}function i(e,n,i){this.bufferSize=null==e?Number.MAX_VALUE:e,this.windowSize=null==n?Number.MAX_VALUE:n,this.scheduler=i||je,this.q=[],this.observers=[],this.isStopped=!1,this.isDisposed=!1,this.hasError=!1,this.error=null,t.call(this,r)}return n.prototype.dispose=function(){if(this.observer.dispose(),!this.subject.isDisposed){var t=this.subject.observers.indexOf(this.observer);this.subject.observers.splice(t,1)}},le(i,t),fe(i.prototype,Fe,{hasObservers:function(){return this.observers.length>0},_trim:function(t){for(;this.q.length>this.bufferSize;)this.q.shift();for(;this.q.length>0&&t-this.q[0].interval>this.windowSize;)this.q.shift()},onNext:function(t){var n;if(e.call(this),!this.isStopped){var r=this.scheduler.now();this.q.push({interval:r,value:t}),this._trim(r);for(var i=this.observers.slice(0),o=0,s=i.length;s>o;o++)n=i[o],n.onNext(t),n.ensureActive()}},onError:function(t){var n;if(e.call(this),!this.isStopped){this.isStopped=!0,this.error=t,this.hasError=!0;var r=this.scheduler.now();this._trim(r);for(var i=this.observers.slice(0),o=0,s=i.length;s>o;o++)n=i[o],n.onError(t),n.ensureActive();this.observers=[]}},onCompleted:function(){var t;if(e.call(this),!this.isStopped){this.isStopped=!0;var n=this.scheduler.now();this._trim(n);for(var r=this.observers.slice(0),i=0,o=r.length;o>i;i++)t=r[i],t.onCompleted(),t.ensureActive();this.observers=[]}},dispose:function(){this.isDisposed=!0,this.observers=null}}),i}($e);"function"==typeof define&&"object"==typeof define.amd&&define.amd?(S.Rx=j,define(function(){return j})):N&&A?_?(A.exports=j).Rx=j:N.Rx=j:S.Rx=j}).call(this); \ No newline at end of file diff --git a/ajax/libs/rxjs/2.2.28/rx.lite.extras.js b/ajax/libs/rxjs/2.2.28/rx.lite.extras.js new file mode 100644 index 000000000..fe97f3206 --- /dev/null +++ b/ajax/libs/rxjs/2.2.28/rx.lite.extras.js @@ -0,0 +1,664 @@ +// 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 (typeof define === 'function' && define.amd) { + define(['rx', 'exports'], function (Rx, exports) { + root.Rx = factory(root, exports, Rx); + return root.Rx; + }); + } 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, + observableNever = Observable.never, + observableThrow = Observable.throwException, + AnonymousObservable = Rx.AnonymousObservable, + Observer = Rx.Observer, + Subject = Rx.Subject, + internals = Rx.internals, + helpers = Rx.helpers, + ScheduledObserver = internals.ScheduledObserver, + SingleAssignmentDisposable = Rx.SingleAssignmentDisposable, + CompositeDisposable = Rx.CompositeDisposable, + RefCountDisposable = Rx.RefCountDisposable, + disposableEmpty = Rx.Disposable.empty, + immediateScheduler = Rx.Scheduler.immediate, + defaultKeySerializer = helpers.defaultKeySerializer, + addRef = Rx.internals.addRef, + identity = helpers.identity, + isPromise = helpers.isPromise, + inherits = internals.inherits, + noop = helpers.noop, + observableFromPromise = Observable.fromPromise, + slice = Array.prototype.slice; + + function argsOrArray(args, idx) { + return args.length === 1 && Array.isArray(args[idx]) ? + args[idx] : + slice.call(args); + } + + var argumentOutOfRange = 'Argument out of range'; + + function ScheduledDisposable(scheduler, disposable) { + this.scheduler = scheduler; + this.disposable = disposable; + this.isDisposed = false; + } + + ScheduledDisposable.prototype.dispose = function () { + var parent = this; + this.scheduler.schedule(function () { + if (!parent.isDisposed) { + parent.isDisposed = true; + parent.disposable.dispose(); + } + }); + }; + + var CheckedObserver = (function (_super) { + inherits(CheckedObserver, _super); + + function CheckedObserver(observer) { + _super.call(this); + this._observer = observer; + this._state = 0; // 0 - idle, 1 - busy, 2 - done + } + + var CheckedObserverPrototype = CheckedObserver.prototype; + + CheckedObserverPrototype.onNext = function (value) { + this.checkAccess(); + try { + this._observer.onNext(value); + } catch (e) { + throw e; + } finally { + this._state = 0; + } + }; + + CheckedObserverPrototype.onError = function (err) { + this.checkAccess(); + try { + this._observer.onError(err); + } catch (e) { + throw e; + } finally { + this._state = 2; + } + }; + + CheckedObserverPrototype.onCompleted = function () { + this.checkAccess(); + try { + this._observer.onCompleted(); + } catch (e) { + throw e; + } finally { + this._state = 2; + } + }; + + CheckedObserverPrototype.checkAccess = function () { + if (this._state === 1) { throw new Error('Re-entrancy detected'); } + if (this._state === 2) { throw new Error('Observer completed'); } + if (this._state === 0) { this._state = 1; } + }; + + return CheckedObserver; + }(Observer)); + + /** @private */ + var ObserveOnObserver = (function (_super) { + inherits(ObserveOnObserver, _super); + + /** @private */ + function ObserveOnObserver() { + _super.apply(this, arguments); + } + + /** @private */ + ObserveOnObserver.prototype.next = function (value) { + _super.prototype.next.call(this, value); + this.ensureActive(); + }; + + /** @private */ + ObserveOnObserver.prototype.error = function (e) { + _super.prototype.error.call(this, e); + this.ensureActive(); + }; + + /** @private */ + ObserveOnObserver.prototype.completed = function () { + _super.prototype.completed.call(this); + this.ensureActive(); + }; + + return ObserveOnObserver; + })(ScheduledObserver); + + /** + * Wraps the source sequence in order to run its observer callbacks on the specified scheduler. + * + * This only invokes observer callbacks on a scheduler. In case the subscription and/or unsubscription actions have side-effects + * that require to be run on a scheduler, use subscribeOn. + * + * @param {Scheduler} scheduler Scheduler to notify observers on. + * @returns {Observable} The source sequence whose observations happen on the specified scheduler. + */ + observableProto.observeOn = function (scheduler) { + var source = this; + return new AnonymousObservable(function (observer) { + return source.subscribe(new ObserveOnObserver(scheduler, observer)); + }); + }; + + /** + * Wraps the source sequence in order to run its subscription and unsubscription logic on the specified scheduler. This operation is not commonly used; + * see the remarks section for more information on the distinction between subscribeOn and observeOn. + + * This only performs the side-effects of subscription and unsubscription on the specified scheduler. In order to invoke observer + * callbacks on a scheduler, use observeOn. + + * @param {Scheduler} scheduler Scheduler to perform subscription and unsubscription actions on. + * @returns {Observable} The source sequence whose subscriptions and unsubscriptions happen on the specified scheduler. + */ + observableProto.subscribeOn = function (scheduler) { + var source = this; + return new AnonymousObservable(function (observer) { + var m = new SingleAssignmentDisposable(), d = new SerialDisposable(); + d.setDisposable(m); + m.setDisposable(scheduler.schedule(function () { + d.setDisposable(new ScheduledDisposable(scheduler, source.subscribe(observer))); + })); + return d; + }); + }; + + /** + * Constructs an observable sequence that depends on a resource object, whose lifetime is tied to the resulting observable sequence's lifetime. + * + * @example + * var res = Rx.Observable.using(function () { return new AsyncSubject(); }, function (s) { return s; }); + * @param {Function} resourceFactory Factory function to obtain a resource object. + * @param {Function} observableFactory Factory function to obtain an observable sequence that depends on the obtained resource. + * @returns {Observable} An observable sequence whose lifetime controls the lifetime of the dependent resource object. + */ + Observable.using = function (resourceFactory, observableFactory) { + return new AnonymousObservable(function (observer) { + var disposable = disposableEmpty, resource, source; + try { + resource = resourceFactory(); + if (resource) { + disposable = resource; + } + source = observableFactory(resource); + } catch (exception) { + return new CompositeDisposable(observableThrow(exception).subscribe(observer), disposable); + } + return new CompositeDisposable(source.subscribe(observer), disposable); + }); + }; + + /** + * Propagates the observable sequence or Promise that reacts first. + * @param {Observable} rightSource Second observable sequence or Promise. + * @returns {Observable} {Observable} An observable sequence that surfaces either of the given sequences, whichever reacted first. + */ + observableProto.amb = function (rightSource) { + var leftSource = this; + return new AnonymousObservable(function (observer) { + var choice, + leftChoice = 'L', rightChoice = 'R', + leftSubscription = new SingleAssignmentDisposable(), + rightSubscription = new SingleAssignmentDisposable(); + + isPromise(rightSource) && (rightSource = observableFromPromise(rightSource)); + + function choiceL() { + if (!choice) { + choice = leftChoice; + rightSubscription.dispose(); + } + } + + function choiceR() { + if (!choice) { + choice = rightChoice; + leftSubscription.dispose(); + } + } + + leftSubscription.setDisposable(leftSource.subscribe(function (left) { + choiceL(); + if (choice === leftChoice) { + observer.onNext(left); + } + }, function (err) { + choiceL(); + if (choice === leftChoice) { + observer.onError(err); + } + }, function () { + choiceL(); + if (choice === leftChoice) { + observer.onCompleted(); + } + })); + + rightSubscription.setDisposable(rightSource.subscribe(function (right) { + choiceR(); + if (choice === rightChoice) { + observer.onNext(right); + } + }, function (err) { + choiceR(); + if (choice === rightChoice) { + observer.onError(err); + } + }, function () { + choiceR(); + if (choice === rightChoice) { + observer.onCompleted(); + } + })); + + return new CompositeDisposable(leftSubscription, rightSubscription); + }); + }; + + /** + * Propagates the observable sequence or Promise that reacts first. + * + * @example + * var = Rx.Observable.amb(xs, ys, zs); + * @returns {Observable} An observable sequence that surfaces any of the given sequences, whichever reacted first. + */ + Observable.amb = function () { + var acc = observableNever(), + items = argsOrArray(arguments, 0); + function func(previous, current) { + return previous.amb(current); + } + for (var i = 0, len = items.length; i < len; i++) { + acc = func(acc, items[i]); + } + return acc; + }; + + /** + * Continues an observable sequence that is terminated normally or by an exception with the next observable sequence. + * @param {Observable} second Second observable sequence used to produce results after the first sequence terminates. + * @returns {Observable} An observable sequence that concatenates the first and second sequence, even if the first sequence terminates exceptionally. + */ + observableProto.onErrorResumeNext = function (second) { + if (!second) { + throw new Error('Second observable is required'); + } + return onErrorResumeNext([this, second]); + }; + + /** + * Continues an observable sequence that is terminated normally or by an exception with the next observable sequence. + * + * @example + * 1 - res = Rx.Observable.onErrorResumeNext(xs, ys, zs); + * 1 - res = Rx.Observable.onErrorResumeNext([xs, ys, zs]); + * @returns {Observable} An observable sequence that concatenates the source sequences, even if a sequence terminates exceptionally. + */ + var onErrorResumeNext = Observable.onErrorResumeNext = function () { + var sources = argsOrArray(arguments, 0); + return new AnonymousObservable(function (observer) { + var pos = 0, subscription = new SerialDisposable(), + cancelable = immediateScheduler.scheduleRecursive(function (self) { + var current, d; + if (pos < sources.length) { + current = sources[pos++]; + isPromise(current) && (current = observableFromPromise(current)); + d = new SingleAssignmentDisposable(); + subscription.setDisposable(d); + d.setDisposable(current.subscribe(observer.onNext.bind(observer), function () { + self(); + }, function () { + self(); + })); + } else { + observer.onCompleted(); + } + }); + return new CompositeDisposable(subscription, cancelable); + }); + }; + + /** + * 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; + }); + }; + + /** + * Projects each element of an observable sequence into zero or more windows which are produced based on element count information. + * + * var res = xs.windowWithCount(10); + * var res = xs.windowWithCount(10, 1); + * @param {Number} count Length of each window. + * @param {Number} [skip] Number of elements to skip between creation of consecutive windows. If not specified, defaults to the count. + * @returns {Observable} An observable sequence of windows. + */ + observableProto.windowWithCount = function (count, skip) { + var source = this; + if (count <= 0) { + throw new Error(argumentOutOfRange); + } + if (arguments.length === 1) { + skip = count; + } + if (skip <= 0) { + throw new Error(argumentOutOfRange); + } + return new AnonymousObservable(function (observer) { + var m = new SingleAssignmentDisposable(), + refCountDisposable = new RefCountDisposable(m), + n = 0, + q = [], + createWindow = function () { + var s = new Subject(); + q.push(s); + observer.onNext(addRef(s, refCountDisposable)); + }; + createWindow(); + m.setDisposable(source.subscribe(function (x) { + var s; + for (var i = 0, len = q.length; i < len; i++) { + q[i].onNext(x); + } + var c = n - count + 1; + if (c >= 0 && c % skip === 0) { + s = q.shift(); + s.onCompleted(); + } + n++; + if (n % skip === 0) { + createWindow(); + } + }, function (exception) { + while (q.length > 0) { + q.shift().onError(exception); + } + observer.onError(exception); + }, function () { + while (q.length > 0) { + q.shift().onCompleted(); + } + observer.onCompleted(); + })); + return refCountDisposable; + }); + }; + + /** + * Returns the elements of the specified sequence or the specified value in a singleton sequence if the sequence is empty. + * + * var res = obs = xs.defaultIfEmpty(); + * 2 - obs = xs.defaultIfEmpty(false); + * + * @memberOf Observable# + * @param defaultValue The value to return if the sequence is empty. If not provided, this defaults to null. + * @returns {Observable} An observable sequence that contains the specified default value if the source is empty; otherwise, the elements of the source itself. + */ + observableProto.defaultIfEmpty = function (defaultValue) { + var source = this; + if (defaultValue === undefined) { + defaultValue = null; + } + return new AnonymousObservable(function (observer) { + var found = false; + return source.subscribe(function (x) { + found = true; + observer.onNext(x); + }, observer.onError.bind(observer), function () { + if (!found) { + observer.onNext(defaultValue); + } + observer.onCompleted(); + }); + }); + }; + + /** + * Returns an observable sequence that contains only distinct elements according to the keySelector and the comparer. + * Usage of this operator should be considered carefully due to the maintenance of an internal lookup structure which can grow large. + * + * @example + * var res = obs = xs.distinct(); + * 2 - obs = xs.distinct(function (x) { return x.id; }); + * 2 - obs = xs.distinct(function (x) { return x.id; }, function (x) { return x.toString(); }); + * @param {Function} [keySelector] A function to compute the comparison key for each element. + * @param {Function} [keySerializer] Used to serialize the given object into a string for object comparison. + * @returns {Observable} An observable sequence only containing the distinct elements, based on a computed key value, from the source sequence. + */ + observableProto.distinct = function (keySelector, keySerializer) { + var source = this; + keySelector || (keySelector = identity); + keySerializer || (keySerializer = defaultKeySerializer); + return new AnonymousObservable(function (observer) { + var hashSet = {}; + return source.subscribe(function (x) { + var key, serializedKey, otherKey, hasMatch = false; + try { + key = keySelector(x); + serializedKey = keySerializer(key); + } catch (exception) { + observer.onError(exception); + return; + } + for (otherKey in hashSet) { + if (serializedKey === otherKey) { + hasMatch = true; + break; + } + } + if (!hasMatch) { + hashSet[serializedKey] = null; + observer.onNext(x); + } + }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); + }); + }; + + /** + * Groups the elements of an observable sequence according to a specified key selector function and comparer and selects the resulting elements by using a specified function. + * + * @example + * var res = observable.groupBy(function (x) { return x.id; }); + * 2 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }); + * 3 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }, function (x) { return x.toString(); }); + * @param {Function} keySelector A function to extract the key for each element. + * @param {Function} [elementSelector] A function to map each source element to an element in an observable group. + * @param {Function} [keySerializer] Used to serialize the given object into a string for object comparison. + * @returns {Observable} A sequence of observable groups, each of which corresponds to a unique key value, containing all elements that share that same key value. + */ + observableProto.groupBy = function (keySelector, elementSelector, keySerializer) { + return this.groupByUntil(keySelector, elementSelector, function () { + return observableNever(); + }, keySerializer); + }; + + /** + * Groups the elements of an observable sequence according to a specified key selector function. + * A duration selector function is used to control the lifetime of groups. When a group expires, it receives an OnCompleted notification. When a new element with the same + * key value as a reclaimed group occurs, the group will be reborn with a new lifetime request. + * + * @example + * var res = observable.groupByUntil(function (x) { return x.id; }, null, function () { return Rx.Observable.never(); }); + * 2 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }, function () { return Rx.Observable.never(); }); + * 3 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }, function () { return Rx.Observable.never(); }, function (x) { return x.toString(); }); + * @param {Function} keySelector A function to extract the key for each element. + * @param {Function} durationSelector A function to signal the expiration of a group. + * @param {Function} [keySerializer] Used to serialize the given object into a string for object comparison. + * @returns {Observable} + * A sequence of observable groups, each of which corresponds to a unique key value, containing all elements that share that same key value. + * If a group's lifetime expires, a new group with the same key value can be created once an element with such a key value is encoutered. + * + */ + observableProto.groupByUntil = function (keySelector, elementSelector, durationSelector, keySerializer) { + var source = this; + elementSelector || (elementSelector = identity); + keySerializer || (keySerializer = defaultKeySerializer); + return new AnonymousObservable(function (observer) { + var map = {}, + groupDisposable = new CompositeDisposable(), + refCountDisposable = new RefCountDisposable(groupDisposable); + groupDisposable.add(source.subscribe(function (x) { + var duration, durationGroup, element, fireNewMapEntry, group, key, serializedKey, md, writer, w; + try { + key = keySelector(x); + serializedKey = keySerializer(key); + } catch (e) { + for (w in map) { + map[w].onError(e); + } + observer.onError(e); + return; + } + fireNewMapEntry = false; + try { + writer = map[serializedKey]; + if (!writer) { + writer = new Subject(); + map[serializedKey] = writer; + fireNewMapEntry = true; + } + } catch (e) { + for (w in map) { + map[w].onError(e); + } + observer.onError(e); + return; + } + if (fireNewMapEntry) { + group = new GroupedObservable(key, writer, refCountDisposable); + durationGroup = new GroupedObservable(key, writer); + try { + duration = durationSelector(durationGroup); + } catch (e) { + for (w in map) { + map[w].onError(e); + } + observer.onError(e); + return; + } + observer.onNext(group); + md = new SingleAssignmentDisposable(); + groupDisposable.add(md); + var expire = function () { + if (serializedKey in map) { + delete map[serializedKey]; + writer.onCompleted(); + } + groupDisposable.remove(md); + }; + md.setDisposable(duration.take(1).subscribe(noop, function (exn) { + for (w in map) { + map[w].onError(exn); + } + observer.onError(exn); + }, function () { + expire(); + })); + } + try { + element = elementSelector(x); + } catch (e) { + for (w in map) { + map[w].onError(e); + } + observer.onError(e); + return; + } + writer.onNext(element); + }, function (ex) { + for (var w in map) { + map[w].onError(ex); + } + observer.onError(ex); + }, function () { + for (var w in map) { + map[w].onCompleted(); + } + observer.onCompleted(); + })); + return refCountDisposable; + }); + }; + + /** @private */ + var GroupedObservable = (function (_super) { + inherits(GroupedObservable, _super); + + function subscribe(observer) { + return this.underlyingObservable.subscribe(observer); + } + + /** + * @constructor + * @private + */ + function GroupedObservable(key, underlyingObservable, mergedDisposable) { + _super.call(this, subscribe); + this.key = key; + this.underlyingObservable = !mergedDisposable ? + underlyingObservable : + new AnonymousObservable(function (observer) { + return new CompositeDisposable(mergedDisposable.getDisposable(), underlyingObservable.subscribe(observer)); + }); + } + + return GroupedObservable; + }(Observable)); + + return Rx; +})); \ No newline at end of file diff --git a/ajax/libs/rxjs/2.2.28/rx.lite.extras.min.js b/ajax/libs/rxjs/2.2.28/rx.lite.extras.min.js new file mode 100644 index 000000000..fbd67e991 --- /dev/null +++ b/ajax/libs/rxjs/2.2.28/rx.lite.extras.min.js @@ -0,0 +1 @@ +(function(t){var e={"boolean":!1,"function":!0,object:!0,number:!1,string:!1,undefined:!1},n=e[typeof window]&&window||this,r=e[typeof exports]&&exports&&!exports.nodeType&&exports,i=e[typeof module]&&module&&!module.nodeType&&module,o=(i&&i.exports===r&&r,e[typeof global]&&global);!o||o.global!==o&&o.window!==o||(n=o),"function"==typeof define&&define.amd?define(["rx","exports"],function(e,r){return n.Rx=t(n,r,e),n.Rx}):"object"==typeof module&&module&&module.exports===r?module.exports=t(n,module.exports,require("./rx")):n.Rx=t(n,{},n.Rx)}).call(this,function(t,e,n,r){function i(t,e){return 1===t.length&&Array.isArray(t[e])?t[e]:_.call(t)}function o(t,e){this.scheduler=t,this.disposable=e,this.isDisposed=!1}var s=n.Observable,u=s.prototype,c=s.never,a=s.throwException,h=n.AnonymousObservable,l=n.Observer,f=n.Subject,p=n.internals,d=n.helpers,b=p.ScheduledObserver,v=n.SingleAssignmentDisposable,m=n.CompositeDisposable,y=n.RefCountDisposable,w=n.Disposable.empty,g=n.Scheduler.immediate,E=d.defaultKeySerializer,x=n.internals.addRef,C=d.identity,D=d.isPromise,S=p.inherits,N=d.noop,A=s.fromPromise,_=Array.prototype.slice,O="Argument out of range";o.prototype.dispose=function(){var t=this;this.scheduler.schedule(function(){t.isDisposed||(t.isDisposed=!0,t.disposable.dispose())})},function(t){function e(e){t.call(this),this._observer=e,this._state=0}S(e,t);var n=e.prototype;return n.onNext=function(t){this.checkAccess();try{this._observer.onNext(t)}catch(e){throw e}finally{this._state=0}},n.onError=function(t){this.checkAccess();try{this._observer.onError(t)}catch(e){throw e}finally{this._state=2}},n.onCompleted=function(){this.checkAccess();try{this._observer.onCompleted()}catch(t){throw t}finally{this._state=2}},n.checkAccess=function(){if(1===this._state)throw Error("Re-entrancy detected");if(2===this._state)throw Error("Observer completed");0===this._state&&(this._state=1)},e}(l);var j=function(t){function e(){t.apply(this,arguments)}return S(e,t),e.prototype.next=function(e){t.prototype.next.call(this,e),this.ensureActive()},e.prototype.error=function(e){t.prototype.error.call(this,e),this.ensureActive()},e.prototype.completed=function(){t.prototype.completed.call(this),this.ensureActive()},e}(b);u.observeOn=function(t){var e=this;return new h(function(n){return e.subscribe(new j(t,n))})},u.subscribeOn=function(t){var e=this;return new h(function(n){var r=new v,i=new SerialDisposable;return i.setDisposable(r),r.setDisposable(t.schedule(function(){i.setDisposable(new o(t,e.subscribe(n)))})),i})},s.using=function(t,e){return new h(function(n){var r,i,o=w;try{r=t(),r&&(o=r),i=e(r)}catch(s){return new m(a(s).subscribe(n),o)}return new m(i.subscribe(n),o)})},u.amb=function(t){var e=this;return new h(function(n){function r(){o||(o=s,a.dispose())}function i(){o||(o=u,c.dispose())}var o,s="L",u="R",c=new v,a=new v;return D(t)&&(t=A(t)),c.setDisposable(e.subscribe(function(t){r(),o===s&&n.onNext(t)},function(t){r(),o===s&&n.onError(t)},function(){r(),o===s&&n.onCompleted()})),a.setDisposable(t.subscribe(function(t){i(),o===u&&n.onNext(t)},function(t){i(),o===u&&n.onError(t)},function(){i(),o===u&&n.onCompleted()})),new m(c,a)})},s.amb=function(){function t(t,e){return t.amb(e)}for(var e=c(),n=i(arguments,0),r=0,o=n.length;o>r;r++)e=t(e,n[r]);return e},u.onErrorResumeNext=function(t){if(!t)throw Error("Second observable is required");return R([this,t])};var R=s.onErrorResumeNext=function(){var t=i(arguments,0);return new h(function(e){var n=0,r=new SerialDisposable,i=g.scheduleRecursive(function(i){var o,s;t.length>n?(o=t[n++],D(o)&&(o=A(o)),s=new v,r.setDisposable(s),s.setDisposable(o.subscribe(e.onNext.bind(e),function(){i()},function(){i()}))):e.onCompleted()});return new m(r,i)})};u.bufferWithCount=function(t,e){return"number"!=typeof e&&(e=t),this.windowWithCount(t,e).selectMany(function(t){return t.toArray()}).where(function(t){return t.length>0})},u.windowWithCount=function(t,e){var n=this;if(0>=t)throw Error(O);if(1===arguments.length&&(e=t),0>=e)throw Error(O);return new h(function(r){var i=new v,o=new y(i),s=0,u=[],c=function(){var t=new f;u.push(t),r.onNext(x(t,o))};return c(),i.setDisposable(n.subscribe(function(n){for(var r,i=0,o=u.length;o>i;i++)u[i].onNext(n);var a=s-t+1;a>=0&&0===a%e&&(r=u.shift(),r.onCompleted()),s++,0===s%e&&c()},function(t){for(;u.length>0;)u.shift().onError(t);r.onError(t)},function(){for(;u.length>0;)u.shift().onCompleted();r.onCompleted()})),o})},u.defaultIfEmpty=function(t){var e=this;return t===r&&(t=null),new h(function(n){var r=!1;return e.subscribe(function(t){r=!0,n.onNext(t)},n.onError.bind(n),function(){r||n.onNext(t),n.onCompleted()})})},u.distinct=function(t,e){var n=this;return t||(t=C),e||(e=E),new h(function(i){var o={};return n.subscribe(function(n){var s,u,c,a=!1;try{s=t(n),u=e(s)}catch(h){return i.onError(h),r}for(c in o)if(u===c){a=!0;break}a||(o[u]=null,i.onNext(n))},i.onError.bind(i),i.onCompleted.bind(i))})},u.groupBy=function(t,e,n){return this.groupByUntil(t,e,function(){return c()},n)},u.groupByUntil=function(t,e,n,i){var o=this;return e||(e=C),i||(i=E),new h(function(s){var u={},c=new m,a=new y(c);return c.add(o.subscribe(function(o){var h,l,p,d,b,m,y,w,g,E;try{m=t(o),y=i(m)}catch(x){for(E in u)u[E].onError(x);return s.onError(x),r}d=!1;try{g=u[y],g||(g=new f,u[y]=g,d=!0)}catch(x){for(E in u)u[E].onError(x);return s.onError(x),r}if(d){b=new W(m,g,a),l=new W(m,g);try{h=n(l)}catch(x){for(E in u)u[E].onError(x);return s.onError(x),r}s.onNext(b),w=new v,c.add(w);var C=function(){y in u&&(delete u[y],g.onCompleted()),c.remove(w)};w.setDisposable(h.take(1).subscribe(N,function(t){for(E in u)u[E].onError(t);s.onError(t)},function(){C()}))}try{p=e(o)}catch(x){for(E in u)u[E].onError(x);return s.onError(x),r}g.onNext(p)},function(t){for(var e in u)u[e].onError(t);s.onError(t)},function(){for(var t in u)u[t].onCompleted();s.onCompleted()})),a})};var W=function(t){function e(t){return this.underlyingObservable.subscribe(t)}function n(n,r,i){t.call(this,e),this.key=n,this.underlyingObservable=i?new h(function(t){return new m(i.getDisposable(),r.subscribe(t))}):r}return S(n,t),n}(s);return n}); \ No newline at end of file diff --git a/ajax/libs/rxjs/2.2.28/rx.lite.js b/ajax/libs/rxjs/2.2.28/rx.lite.js new file mode 100644 index 000000000..0988b3648 --- /dev/null +++ b/ajax/libs/rxjs/2.2.28/rx.lite.js @@ -0,0 +1,5852 @@ +// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. + +;(function (undefined) { + + var objectTypes = { + 'boolean': false, + 'function': true, + 'object': true, + 'number': false, + 'string': false, + 'undefined': false + }; + + var root = (objectTypes[typeof window] && window) || this, + freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports, + freeModule = objectTypes[typeof module] && module && !module.nodeType && module, + moduleExports = freeModule && freeModule.exports === freeExports && freeExports, + freeGlobal = objectTypes[typeof global] && global; + + if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal)) { + root = freeGlobal; + } + + var Rx = { + internals: {}, + config: { + Promise: root.Promise // Detect if promise exists + }, + helpers: { } + }; + + // Defaults + var noop = Rx.helpers.noop = function () { }, + identity = Rx.helpers.identity = function (x) { return x; }, + pluck = Rx.helpers.pluck = function (property) { return function (x) { return x[property]; }; }, + just = Rx.helpers.just = function (value) { return function () { return value; }; }, + defaultNow = Rx.helpers.defaultNow = Date.now, + defaultComparer = Rx.helpers.defaultComparer = function (x, y) { return isEqual(x, y); }, + defaultSubComparer = Rx.helpers.defaultSubComparer = function (x, y) { return x > y ? 1 : (x < y ? -1 : 0); }, + defaultKeySerializer = Rx.helpers.defaultKeySerializer = function (x) { return x.toString(); }, + defaultError = Rx.helpers.defaultError = function (err) { throw err; }, + isPromise = Rx.helpers.isPromise = function (p) { return !!p && typeof p.then === 'function' && p.then !== Rx.Observable.prototype.then; }, + asArray = Rx.helpers.asArray = function () { return Array.prototype.slice.call(arguments); }, + not = Rx.helpers.not = function (a) { return !a; }; + + // Errors + var sequenceContainsNoElements = 'Sequence contains no elements.'; + var argumentOutOfRange = 'Argument out of range'; + var objectDisposed = 'Object has been disposed'; + function checkDisposed() { if (this.isDisposed) { throw new Error(objectDisposed); } } + + // Shim in iterator support + var $iterator$ = (typeof Symbol === 'object' && Symbol.iterator) || + '_es6shim_iterator_'; + // Firefox ships a partial implementation using the name @@iterator. + // https://bugzilla.mozilla.org/show_bug.cgi?id=907077#c14 + // So use that name if we detect it. + if (root.Set && typeof new root.Set()['@@iterator'] === 'function') { + $iterator$ = '@@iterator'; + } + var doneEnumerator = { done: true, value: undefined }; + + /** `Object#toString` result shortcuts */ + var argsClass = '[object Arguments]', + arrayClass = '[object Array]', + boolClass = '[object Boolean]', + dateClass = '[object Date]', + errorClass = '[object Error]', + funcClass = '[object Function]', + numberClass = '[object Number]', + objectClass = '[object Object]', + regexpClass = '[object RegExp]', + stringClass = '[object String]'; + + var toString = Object.prototype.toString, + hasOwnProperty = Object.prototype.hasOwnProperty, + supportsArgsClass = toString.call(arguments) == argsClass, // For less -1); + } + }); + } + } + stackA.pop(); + stackB.pop(); + + return result; + } + var slice = Array.prototype.slice; + function argsOrArray(args, idx) { + return args.length === 1 && Array.isArray(args[idx]) ? + args[idx] : + slice.call(args); + } + var hasProp = {}.hasOwnProperty; + + /** @private */ + var inherits = this.inherits = Rx.internals.inherits = function (child, parent) { + function __() { this.constructor = child; } + __.prototype = parent.prototype; + child.prototype = new __(); + }; + + /** @private */ + var addProperties = Rx.internals.addProperties = function (obj) { + var sources = slice.call(arguments, 1); + for (var i = 0, len = sources.length; i < len; i++) { + var source = sources[i]; + for (var prop in source) { + obj[prop] = source[prop]; + } + } + }; + + // Rx Utils + var addRef = Rx.internals.addRef = function (xs, r) { + return new AnonymousObservable(function (observer) { + return new CompositeDisposable(r.getDisposable(), xs.subscribe(observer)); + }); + }; + + // Collection polyfills + function arrayInitialize(count, factory) { + var a = new Array(count); + for (var i = 0; i < count; i++) { + a[i] = factory(); + } + return a; + } + + // Collections + var IndexedItem = function (id, value) { + this.id = id; + this.value = value; + }; + + IndexedItem.prototype.compareTo = function (other) { + var c = this.value.compareTo(other.value); + if (c === 0) { + c = this.id - other.id; + } + return c; + }; + + // Priority Queue for Scheduling + var PriorityQueue = Rx.internals.PriorityQueue = function (capacity) { + this.items = new Array(capacity); + this.length = 0; + }; + + var priorityProto = PriorityQueue.prototype; + priorityProto.isHigherPriority = function (left, right) { + return this.items[left].compareTo(this.items[right]) < 0; + }; + + priorityProto.percolate = function (index) { + if (index >= this.length || index < 0) { + return; + } + var parent = index - 1 >> 1; + if (parent < 0 || parent === index) { + return; + } + if (this.isHigherPriority(index, parent)) { + var temp = this.items[index]; + this.items[index] = this.items[parent]; + this.items[parent] = temp; + this.percolate(parent); + } + }; + + priorityProto.heapify = function (index) { + if (index === undefined) { + index = 0; + } + if (index >= this.length || index < 0) { + return; + } + var left = 2 * index + 1, + right = 2 * index + 2, + first = index; + if (left < this.length && this.isHigherPriority(left, first)) { + first = left; + } + if (right < this.length && this.isHigherPriority(right, first)) { + first = right; + } + if (first !== index) { + var temp = this.items[index]; + this.items[index] = this.items[first]; + this.items[first] = temp; + this.heapify(first); + } + }; + + priorityProto.peek = function () { return this.items[0].value; }; + + priorityProto.removeAt = function (index) { + this.items[index] = this.items[--this.length]; + delete this.items[this.length]; + this.heapify(); + }; + + priorityProto.dequeue = function () { + var result = this.peek(); + this.removeAt(0); + return result; + }; + + priorityProto.enqueue = function (item) { + var index = this.length++; + this.items[index] = new IndexedItem(PriorityQueue.count++, item); + this.percolate(index); + }; + + priorityProto.remove = function (item) { + for (var i = 0; i < this.length; i++) { + if (this.items[i].value === item) { + this.removeAt(i); + return true; + } + } + return false; + }; + PriorityQueue.count = 0; + /** + * Represents a group of disposable resources that are disposed together. + * @constructor + */ + var CompositeDisposable = Rx.CompositeDisposable = function () { + this.disposables = argsOrArray(arguments, 0); + this.isDisposed = false; + this.length = this.disposables.length; + }; + + var CompositeDisposablePrototype = CompositeDisposable.prototype; + + /** + * Adds a disposable to the CompositeDisposable or disposes the disposable if the CompositeDisposable is disposed. + * @param {Mixed} item Disposable to add. + */ + CompositeDisposablePrototype.add = function (item) { + if (this.isDisposed) { + item.dispose(); + } else { + this.disposables.push(item); + this.length++; + } + }; + + /** + * Removes and disposes the first occurrence of a disposable from the CompositeDisposable. + * @param {Mixed} item Disposable to remove. + * @returns {Boolean} true if found; false otherwise. + */ + CompositeDisposablePrototype.remove = function (item) { + var shouldDispose = false; + if (!this.isDisposed) { + var idx = this.disposables.indexOf(item); + if (idx !== -1) { + shouldDispose = true; + this.disposables.splice(idx, 1); + this.length--; + item.dispose(); + } + + } + return shouldDispose; + }; + + /** + * Disposes all disposables in the group and removes them from the group. + */ + CompositeDisposablePrototype.dispose = function () { + if (!this.isDisposed) { + this.isDisposed = true; + var currentDisposables = this.disposables.slice(0); + this.disposables = []; + this.length = 0; + + for (var i = 0, len = currentDisposables.length; i < len; i++) { + currentDisposables[i].dispose(); + } + } + }; + + /** + * Removes and disposes all disposables from the CompositeDisposable, but does not dispose the CompositeDisposable. + */ + CompositeDisposablePrototype.clear = function () { + var currentDisposables = this.disposables.slice(0); + this.disposables = []; + this.length = 0; + for (var i = 0, len = currentDisposables.length; i < len; i++) { + currentDisposables[i].dispose(); + } + }; + + /** + * Determines whether the CompositeDisposable contains a specific disposable. + * @param {Mixed} item Disposable to search for. + * @returns {Boolean} true if the disposable was found; otherwise, false. + */ + CompositeDisposablePrototype.contains = function (item) { + return this.disposables.indexOf(item) !== -1; + }; + + /** + * Converts the existing CompositeDisposable to an array of disposables + * @returns {Array} An array of disposable objects. + */ + CompositeDisposablePrototype.toArray = function () { + return this.disposables.slice(0); + }; + + /** + * Provides a set of static methods for creating Disposables. + * + * @constructor + * @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once. + */ + var Disposable = Rx.Disposable = function (action) { + this.isDisposed = false; + this.action = action || noop; + }; + + /** Performs the task of cleaning up resources. */ + Disposable.prototype.dispose = function () { + if (!this.isDisposed) { + this.action(); + this.isDisposed = true; + } + }; + + /** + * Creates a disposable object that invokes the specified action when disposed. + * @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once. + * @return {Disposable} The disposable object that runs the given action upon disposal. + */ + var disposableCreate = Disposable.create = function (action) { return new Disposable(action); }; + + /** + * Gets the disposable that does nothing when disposed. + */ + var disposableEmpty = Disposable.empty = { dispose: noop }; + + var BooleanDisposable = (function () { + function BooleanDisposable (isSingle) { + this.isSingle = isSingle; + this.isDisposed = false; + this.current = null; + } + + var booleanDisposablePrototype = BooleanDisposable.prototype; + + /** + * Gets the underlying disposable. + * @return The underlying disposable. + */ + booleanDisposablePrototype.getDisposable = function () { + return this.current; + }; + + /** + * Sets the underlying disposable. + * @param {Disposable} value The new underlying disposable. + */ + booleanDisposablePrototype.setDisposable = function (value) { + if (this.current && this.isSingle) { + throw new Error('Disposable has already been assigned'); + } + + var shouldDispose = this.isDisposed, old; + if (!shouldDispose) { + old = this.current; + this.current = value; + } + if (old) { + old.dispose(); + } + if (shouldDispose && value) { + value.dispose(); + } + }; + + /** + * Disposes the underlying disposable as well as all future replacements. + */ + booleanDisposablePrototype.dispose = function () { + var old; + if (!this.isDisposed) { + this.isDisposed = true; + old = this.current; + this.current = null; + } + if (old) { + old.dispose(); + } + }; + + return BooleanDisposable; + }()); + + /** + * Represents a disposable resource which only allows a single assignment of its underlying disposable resource. + * If an underlying disposable resource has already been set, future attempts to set the underlying disposable resource will throw an Error. + */ + var SingleAssignmentDisposable = Rx.SingleAssignmentDisposable = (function (super_) { + inherits(SingleAssignmentDisposable, super_); + + function SingleAssignmentDisposable() { + super_.call(this, true); + } + + return SingleAssignmentDisposable; + }(BooleanDisposable)); + + /** + * Represents a disposable resource whose underlying disposable resource can be replaced by another disposable resource, causing automatic disposal of the previous underlying disposable resource. + */ + var SerialDisposable = Rx.SerialDisposable = (function (super_) { + inherits(SerialDisposable, super_); + + function SerialDisposable() { + super_.call(this, false); + } + + return SerialDisposable; + }(BooleanDisposable)); + + /** + * Represents a disposable resource that only disposes its underlying disposable resource when all dependent disposable objects have been disposed. + */ + var RefCountDisposable = Rx.RefCountDisposable = (function () { + + function InnerDisposable(disposable) { + this.disposable = disposable; + this.disposable.count++; + this.isInnerDisposed = false; + } + + InnerDisposable.prototype.dispose = function () { + if (!this.disposable.isDisposed) { + if (!this.isInnerDisposed) { + this.isInnerDisposed = true; + this.disposable.count--; + if (this.disposable.count === 0 && this.disposable.isPrimaryDisposed) { + this.disposable.isDisposed = true; + this.disposable.underlyingDisposable.dispose(); + } + } + } + }; + + /** + * Initializes a new instance of the RefCountDisposable with the specified disposable. + * @constructor + * @param {Disposable} disposable Underlying disposable. + */ + function RefCountDisposable(disposable) { + this.underlyingDisposable = disposable; + this.isDisposed = false; + this.isPrimaryDisposed = false; + this.count = 0; + } + + /** + * Disposes the underlying disposable only when all dependent disposables have been disposed + */ + RefCountDisposable.prototype.dispose = function () { + if (!this.isDisposed) { + if (!this.isPrimaryDisposed) { + this.isPrimaryDisposed = true; + if (this.count === 0) { + this.isDisposed = true; + this.underlyingDisposable.dispose(); + } + } + } + }; + + /** + * Returns a dependent disposable that when disposed decreases the refcount on the underlying disposable. + * @returns {Disposable} A dependent disposable contributing to the reference count that manages the underlying disposable's lifetime. + */ + RefCountDisposable.prototype.getDisposable = function () { + return this.isDisposed ? disposableEmpty : new InnerDisposable(this); + }; + + return RefCountDisposable; + })(); + + var ScheduledItem = Rx.internals.ScheduledItem = function (scheduler, state, action, dueTime, comparer) { + this.scheduler = scheduler; + this.state = state; + this.action = action; + this.dueTime = dueTime; + this.comparer = comparer || defaultSubComparer; + this.disposable = new SingleAssignmentDisposable(); + } + + ScheduledItem.prototype.invoke = function () { + this.disposable.setDisposable(this.invokeCore()); + }; + + ScheduledItem.prototype.compareTo = function (other) { + return this.comparer(this.dueTime, other.dueTime); + }; + + ScheduledItem.prototype.isCancelled = function () { + return this.disposable.isDisposed; + }; + + ScheduledItem.prototype.invokeCore = function () { + return this.action(this.scheduler, this.state); + }; + + /** Provides a set of static properties to access commonly used schedulers. */ + var Scheduler = Rx.Scheduler = (function () { + + function Scheduler(now, schedule, scheduleRelative, scheduleAbsolute) { + this.now = now; + this._schedule = schedule; + this._scheduleRelative = scheduleRelative; + this._scheduleAbsolute = scheduleAbsolute; + } + + function invokeRecImmediate(scheduler, pair) { + var state = pair.first, action = pair.second, group = new CompositeDisposable(), + recursiveAction = function (state1) { + action(state1, function (state2) { + var isAdded = false, isDone = false, + d = scheduler.scheduleWithState(state2, function (scheduler1, state3) { + if (isAdded) { + group.remove(d); + } else { + isDone = true; + } + recursiveAction(state3); + return disposableEmpty; + }); + if (!isDone) { + group.add(d); + isAdded = true; + } + }); + }; + recursiveAction(state); + return group; + } + + function invokeRecDate(scheduler, pair, method) { + var state = pair.first, action = pair.second, group = new CompositeDisposable(), + recursiveAction = function (state1) { + action(state1, function (state2, dueTime1) { + var isAdded = false, isDone = false, + d = scheduler[method].call(scheduler, state2, dueTime1, function (scheduler1, state3) { + if (isAdded) { + group.remove(d); + } else { + isDone = true; + } + recursiveAction(state3); + return disposableEmpty; + }); + if (!isDone) { + group.add(d); + isAdded = true; + } + }); + }; + recursiveAction(state); + return group; + } + + function invokeAction(scheduler, action) { + action(); + return disposableEmpty; + } + + var schedulerProto = Scheduler.prototype; + + /** + * Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation. + * @param {Number} period Period for running the work periodically. + * @param {Function} action Action to be executed. + * @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort). + */ + schedulerProto.schedulePeriodic = function (period, action) { + return this.schedulePeriodicWithState(null, period, function () { + action(); + }); + }; + + /** + * Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation. + * @param {Mixed} state Initial state passed to the action upon the first iteration. + * @param {Number} period Period for running the work periodically. + * @param {Function} action Action to be executed, potentially updating the state. + * @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort). + */ + schedulerProto.schedulePeriodicWithState = function (state, period, action) { + var s = state, id = setInterval(function () { + s = action(s); + }, period); + return disposableCreate(function () { + clearInterval(id); + }); + }; + + /** + * Schedules an action to be executed. + * @param {Function} action Action to execute. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.schedule = function (action) { + return this._schedule(action, invokeAction); + }; + + /** + * Schedules an action to be executed. + * @param state State passed to the action to be executed. + * @param {Function} action Action to be executed. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleWithState = function (state, action) { + return this._schedule(state, action); + }; + + /** + * Schedules an action to be executed after the specified relative due time. + * @param {Function} action Action to execute. + * @param {Number} dueTime Relative time after which to execute the action. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleWithRelative = function (dueTime, action) { + return this._scheduleRelative(action, dueTime, invokeAction); + }; + + /** + * Schedules an action to be executed after dueTime. + * @param {Mixed} state State passed to the action to be executed. + * @param {Function} action Action to be executed. + * @param {Number} dueTime Relative time after which to execute the action. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleWithRelativeAndState = function (state, dueTime, action) { + return this._scheduleRelative(state, dueTime, action); + }; + + /** + * Schedules an action to be executed at the specified absolute due time. + * @param {Function} action Action to execute. + * @param {Number} dueTime Absolute time at which to execute the action. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleWithAbsolute = function (dueTime, action) { + return this._scheduleAbsolute(action, dueTime, invokeAction); + }; + + /** + * Schedules an action to be executed at dueTime. + * @param {Mixed} state State passed to the action to be executed. + * @param {Function} action Action to be executed. + * @param {Number}dueTime Absolute time at which to execute the action. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleWithAbsoluteAndState = function (state, dueTime, action) { + return this._scheduleAbsolute(state, dueTime, action); + }; + + /** + * Schedules an action to be executed recursively. + * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleRecursive = function (action) { + return this.scheduleRecursiveWithState(action, function (_action, self) { + _action(function () { + self(_action); + }); + }); + }; + + /** + * Schedules an action to be executed recursively. + * @param {Mixed} state State passed to the action to be executed. + * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in recursive invocation state. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleRecursiveWithState = function (state, action) { + return this.scheduleWithState({ first: state, second: action }, function (s, p) { + return invokeRecImmediate(s, p); + }); + }; + + /** + * Schedules an action to be executed recursively after a specified relative due time. + * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified relative time. + * @param {Number}dueTime Relative time after which to execute the action for the first time. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleRecursiveWithRelative = function (dueTime, action) { + return this.scheduleRecursiveWithRelativeAndState(action, dueTime, function (_action, self) { + _action(function (dt) { + self(_action, dt); + }); + }); + }; + + /** + * Schedules an action to be executed recursively after a specified relative due time. + * @param {Mixed} state State passed to the action to be executed. + * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state. + * @param {Number}dueTime Relative time after which to execute the action for the first time. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleRecursiveWithRelativeAndState = function (state, dueTime, action) { + return this._scheduleRelative({ first: state, second: action }, dueTime, function (s, p) { + return invokeRecDate(s, p, 'scheduleWithRelativeAndState'); + }); + }; + + /** + * Schedules an action to be executed recursively at a specified absolute due time. + * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified absolute time. + * @param {Number}dueTime Absolute time at which to execute the action for the first time. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleRecursiveWithAbsolute = function (dueTime, action) { + return this.scheduleRecursiveWithAbsoluteAndState(action, dueTime, function (_action, self) { + _action(function (dt) { + self(_action, dt); + }); + }); + }; + + /** + * Schedules an action to be executed recursively at a specified absolute due time. + * @param {Mixed} state State passed to the action to be executed. + * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state. + * @param {Number}dueTime Absolute time at which to execute the action for the first time. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleRecursiveWithAbsoluteAndState = function (state, dueTime, action) { + return this._scheduleAbsolute({ first: state, second: action }, dueTime, function (s, p) { + return invokeRecDate(s, p, 'scheduleWithAbsoluteAndState'); + }); + }; + + /** Gets the current time according to the local machine's system clock. */ + Scheduler.now = defaultNow; + + /** + * Normalizes the specified TimeSpan value to a positive value. + * @param {Number} timeSpan The time span value to normalize. + * @returns {Number} The specified TimeSpan value if it is zero or positive; otherwise, 0 + */ + Scheduler.normalize = function (timeSpan) { + if (timeSpan < 0) { + timeSpan = 0; + } + return timeSpan; + }; + + return Scheduler; + }()); + + var normalizeTime = Scheduler.normalize; + + /** + * Gets a scheduler that schedules work immediately on the current thread. + */ + var immediateScheduler = Scheduler.immediate = (function () { + + function scheduleNow(state, action) { return action(this, state); } + + function scheduleRelative(state, dueTime, action) { + var dt = normalizeTime(dt); + while (dt - this.now() > 0) { } + return action(this, state); + } + + function scheduleAbsolute(state, dueTime, action) { + return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); + } + + return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); + }()); + + /** + * Gets a scheduler that schedules work as soon as possible on the current thread. + */ + var currentThreadScheduler = Scheduler.currentThread = (function () { + var queue; + + function runTrampoline (q) { + var item; + while (q.length > 0) { + item = q.dequeue(); + if (!item.isCancelled()) { + // Note, do not schedule blocking work! + while (item.dueTime - Scheduler.now() > 0) { + } + if (!item.isCancelled()) { + item.invoke(); + } + } + } + } + + function scheduleNow(state, action) { + return this.scheduleWithRelativeAndState(state, 0, action); + } + + function scheduleRelative(state, dueTime, action) { + var dt = this.now() + Scheduler.normalize(dueTime), + si = new ScheduledItem(this, state, action, dt), + t; + if (!queue) { + queue = new PriorityQueue(4); + queue.enqueue(si); + try { + runTrampoline(queue); + } catch (e) { + throw e; + } finally { + queue = null; + } + } else { + queue.enqueue(si); + } + return si.disposable; + } + + function scheduleAbsolute(state, dueTime, action) { + return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); + } + + var currentScheduler = new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); + currentScheduler.scheduleRequired = function () { return queue === null; }; + currentScheduler.ensureTrampoline = function (action) { + if (queue === null) { + return this.schedule(action); + } else { + return action(); + } + }; + + return currentScheduler; + }()); + + var SchedulePeriodicRecursive = Rx.internals.SchedulePeriodicRecursive = (function () { + function tick(command, recurse) { + recurse(0, this._period); + try { + this._state = this._action(this._state); + } catch (e) { + this._cancel.dispose(); + throw e; + } + } + + function SchedulePeriodicRecursive(scheduler, state, period, action) { + this._scheduler = scheduler; + this._state = state; + this._period = period; + this._action = action; + } + + SchedulePeriodicRecursive.prototype.start = function () { + var d = new SingleAssignmentDisposable(); + this._cancel = d; + d.setDisposable(this._scheduler.scheduleRecursiveWithRelativeAndState(0, this._period, tick.bind(this))); + + return d; + }; + + return SchedulePeriodicRecursive; + }()); + + + var scheduleMethod, clearMethod = noop; + (function () { + + var reNative = RegExp('^' + + String(toString) + .replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + .replace(/toString| for [^\]]+/g, '.*?') + '$' + ); + + var setImmediate = typeof (setImmediate = freeGlobal && moduleExports && freeGlobal.setImmediate) == 'function' && + !reNative.test(setImmediate) && setImmediate, + clearImmediate = typeof (clearImmediate = freeGlobal && moduleExports && freeGlobal.clearImmediate) == 'function' && + !reNative.test(clearImmediate) && clearImmediate; + + function postMessageSupported () { + // Ensure not in a worker + if (!root.postMessage || root.importScripts) { return false; } + var isAsync = false, + oldHandler = root.onmessage; + // Test for async + root.onmessage = function () { isAsync = true; }; + root.postMessage('','*'); + root.onmessage = oldHandler; + + return isAsync; + } + + // Use in order, nextTick, setImmediate, postMessage, MessageChannel, script readystatechanged, setTimeout + if (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]') { + scheduleMethod = process.nextTick; + } else if (typeof setImmediate === 'function') { + scheduleMethod = setImmediate; + clearMethod = clearImmediate; + } else if (postMessageSupported()) { + var MSG_PREFIX = 'ms.rx.schedule' + Math.random(), + tasks = {}, + taskId = 0; + + function onGlobalPostMessage(event) { + // Only if we're a match to avoid any other global events + if (typeof event.data === 'string' && event.data.substring(0, MSG_PREFIX.length) === MSG_PREFIX) { + var handleId = event.data.substring(MSG_PREFIX.length), + action = tasks[handleId]; + action(); + delete tasks[handleId]; + } + } + + if (root.addEventListener) { + root.addEventListener('message', onGlobalPostMessage, false); + } else { + root.attachEvent('onmessage', onGlobalPostMessage, false); + } + + scheduleMethod = function (action) { + var currentId = taskId++; + tasks[currentId] = action; + root.postMessage(MSG_PREFIX + currentId, '*'); + }; + } else if (!!root.MessageChannel) { + var channel = new root.MessageChannel(), + channelTasks = {}, + channelTaskId = 0; + + channel.port1.onmessage = function (event) { + var id = event.data, + action = channelTasks[id]; + action(); + delete channelTasks[id]; + }; + + scheduleMethod = function (action) { + var id = channelTaskId++; + channelTasks[id] = action; + channel.port2.postMessage(id); + }; + } else if ('document' in root && 'onreadystatechange' in root.document.createElement('script')) { + + scheduleMethod = function (action) { + var scriptElement = root.document.createElement('script'); + scriptElement.onreadystatechange = function () { + action(); + scriptElement.onreadystatechange = null; + scriptElement.parentNode.removeChild(scriptElement); + scriptElement = null; + }; + root.document.documentElement.appendChild(scriptElement); + }; + + } else { + scheduleMethod = function (action) { return setTimeout(action, 0); }; + clearMethod = clearTimeout; + } + }()); + + /** + * Gets a scheduler that schedules work via a timed callback based upon platform. + */ + var timeoutScheduler = Scheduler.timeout = (function () { + + function scheduleNow(state, action) { + var scheduler = this, + disposable = new SingleAssignmentDisposable(); + var id = scheduleMethod(function () { + if (!disposable.isDisposed) { + disposable.setDisposable(action(scheduler, state)); + } + }); + return new CompositeDisposable(disposable, disposableCreate(function () { + clearMethod(id); + })); + } + + function scheduleRelative(state, dueTime, action) { + var scheduler = this, + dt = Scheduler.normalize(dueTime); + if (dt === 0) { + return scheduler.scheduleWithState(state, action); + } + var disposable = new SingleAssignmentDisposable(); + var id = setTimeout(function () { + if (!disposable.isDisposed) { + disposable.setDisposable(action(scheduler, state)); + } + }, dt); + return new CompositeDisposable(disposable, disposableCreate(function () { + clearTimeout(id); + })); + } + + function scheduleAbsolute(state, dueTime, action) { + return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); + } + + return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); + })(); + + /** + * Represents a notification to an observer. + */ + var Notification = Rx.Notification = (function () { + function Notification(kind, hasValue) { + this.hasValue = hasValue == null ? false : hasValue; + this.kind = kind; + } + + var NotificationPrototype = Notification.prototype; + + /** + * Invokes the delegate corresponding to the notification or the observer's method corresponding to the notification and returns the produced result. + * + * @memberOf Notification + * @param {Any} observerOrOnNext Delegate to invoke for an OnNext notification or Observer to invoke the notification on.. + * @param {Function} onError Delegate to invoke for an OnError notification. + * @param {Function} onCompleted Delegate to invoke for an OnCompleted notification. + * @returns {Any} Result produced by the observation. + */ + NotificationPrototype.accept = function (observerOrOnNext, onError, onCompleted) { + if (arguments.length === 1 && typeof observerOrOnNext === 'object') { + return this._acceptObservable(observerOrOnNext); + } + return this._accept(observerOrOnNext, onError, onCompleted); + }; + + /** + * Returns an observable sequence with a single notification. + * + * @memberOf Notification + * @param {Scheduler} [scheduler] Scheduler to send out the notification calls on. + * @returns {Observable} The observable sequence that surfaces the behavior of the notification upon subscription. + */ + NotificationPrototype.toObservable = function (scheduler) { + var notification = this; + scheduler || (scheduler = immediateScheduler); + return new AnonymousObservable(function (observer) { + return scheduler.schedule(function () { + notification._acceptObservable(observer); + if (notification.kind === 'N') { + observer.onCompleted(); + } + }); + }); + }; + + return Notification; + })(); + + /** + * Creates an object that represents an OnNext notification to an observer. + * @param {Any} value The value contained in the notification. + * @returns {Notification} The OnNext notification containing the value. + */ + var notificationCreateOnNext = Notification.createOnNext = (function () { + + function _accept (onNext) { + return onNext(this.value); + } + + function _acceptObservable(observer) { + return observer.onNext(this.value); + } + + function toString () { + return 'OnNext(' + this.value + ')'; + } + + return function (value) { + var notification = new Notification('N', true); + notification.value = value; + notification._accept = _accept; + notification._acceptObservable = _acceptObservable; + notification.toString = toString; + return notification; + }; + }()); + + /** + * Creates an object that represents an OnError notification to an observer. + * @param {Any} error The exception contained in the notification. + * @returns {Notification} The OnError notification containing the exception. + */ + var notificationCreateOnError = Notification.createOnError = (function () { + + function _accept (onNext, onError) { + return onError(this.exception); + } + + function _acceptObservable(observer) { + return observer.onError(this.exception); + } + + function toString () { + return 'OnError(' + this.exception + ')'; + } + + return function (exception) { + var notification = new Notification('E'); + notification.exception = exception; + notification._accept = _accept; + notification._acceptObservable = _acceptObservable; + notification.toString = toString; + return notification; + }; + }()); + + /** + * Creates an object that represents an OnCompleted notification to an observer. + * @returns {Notification} The OnCompleted notification. + */ + var notificationCreateOnCompleted = Notification.createOnCompleted = (function () { + + function _accept (onNext, onError, onCompleted) { + return onCompleted(); + } + + function _acceptObservable(observer) { + return observer.onCompleted(); + } + + function toString () { + return 'OnCompleted()'; + } + + return function () { + var notification = new Notification('C'); + notification._accept = _accept; + notification._acceptObservable = _acceptObservable; + notification.toString = toString; + return notification; + }; + }()); + + var Enumerator = Rx.internals.Enumerator = function (next) { + this._next = next; + }; + + Enumerator.prototype.next = function () { + return this._next(); + }; + + Enumerator.prototype[$iterator$] = function () { return this; } + + var Enumerable = Rx.internals.Enumerable = function (iterator) { + this._iterator = iterator; + }; + + Enumerable.prototype[$iterator$] = function () { + return this._iterator(); + }; + + Enumerable.prototype.concat = function () { + var sources = this; + return new AnonymousObservable(function (observer) { + var e; + try { + e = sources[$iterator$](); + } catch(err) { + observer.onError(); + return; + } + + var isDisposed, + subscription = new SerialDisposable(); + var cancelable = immediateScheduler.scheduleRecursive(function (self) { + var currentItem; + if (isDisposed) { return; } + + try { + currentItem = e.next(); + } catch (ex) { + observer.onError(ex); + return; + } + + if (currentItem.done) { + observer.onCompleted(); + return; + } + + // Check if promise + var currentValue = currentItem.value; + isPromise(currentValue) && (currentValue = observableFromPromise(currentValue)); + + var d = new SingleAssignmentDisposable(); + subscription.setDisposable(d); + d.setDisposable(currentValue.subscribe( + observer.onNext.bind(observer), + observer.onError.bind(observer), + function () { self(); }) + ); + }); + + return new CompositeDisposable(subscription, cancelable, disposableCreate(function () { + isDisposed = true; + })); + }); + }; + + Enumerable.prototype.catchException = function () { + var sources = this; + return new AnonymousObservable(function (observer) { + var e; + try { + e = sources[$iterator$](); + } catch(err) { + observer.onError(); + return; + } + + var isDisposed, + lastException, + subscription = new SerialDisposable(); + var cancelable = immediateScheduler.scheduleRecursive(function (self) { + if (isDisposed) { return; } + + var currentItem; + try { + currentItem = e.next(); + } catch (ex) { + observer.onError(ex); + return; + } + + if (currentItem.done) { + if (lastException) { + observer.onError(lastException); + } else { + observer.onCompleted(); + } + return; + } + + // Check if promise + var currentValue = currentItem.value; + isPromise(currentValue) && (currentValue = observableFromPromise(currentValue)); + + var d = new SingleAssignmentDisposable(); + subscription.setDisposable(d); + d.setDisposable(currentValue.subscribe( + observer.onNext.bind(observer), + function (exn) { + lastException = exn; + self(); + }, + observer.onCompleted.bind(observer))); + }); + return new CompositeDisposable(subscription, cancelable, disposableCreate(function () { + isDisposed = true; + })); + }); + }; + + var enumerableRepeat = Enumerable.repeat = function (value, repeatCount) { + if (repeatCount == null) { repeatCount = -1; } + return new Enumerable(function () { + var left = repeatCount; + return new Enumerator(function () { + if (left === 0) { return doneEnumerator; } + if (left > 0) { left--; } + return { done: false, value: value }; + }); + }); + }; + + var enumerableFor = Enumerable.forEach = function (source, selector, thisArg) { + selector || (selector = identity); + return new Enumerable(function () { + var index = -1; + return new Enumerator( + function () { + return ++index < source.length ? + { done: false, value: selector.call(thisArg, source[index], index, source) } : + doneEnumerator; + }); + }); + }; + + /** + * Supports push-style iteration over an observable sequence. + */ + var Observer = Rx.Observer = function () { }; + + /** + * Creates a notification callback from an observer. + * + * @param observer Observer object. + * @returns The action that forwards its input notification to the underlying observer. + */ + Observer.prototype.toNotifier = function () { + var observer = this; + return function (n) { + return n.accept(observer); + }; + }; + + /** + * Hides the identity of an observer. + + * @returns An observer that hides the identity of the specified observer. + */ + Observer.prototype.asObserver = function () { + return new AnonymousObserver(this.onNext.bind(this), this.onError.bind(this), this.onCompleted.bind(this)); + }; + + /** + * Creates an observer from the specified OnNext, along with optional OnError, and OnCompleted actions. + * + * @static + * @memberOf Observer + * @param {Function} [onNext] Observer's OnNext action implementation. + * @param {Function} [onError] Observer's OnError action implementation. + * @param {Function} [onCompleted] Observer's OnCompleted action implementation. + * @returns {Observer} The observer object implemented using the given actions. + */ + var observerCreate = Observer.create = function (onNext, onError, onCompleted) { + onNext || (onNext = noop); + onError || (onError = defaultError); + onCompleted || (onCompleted = noop); + return new AnonymousObserver(onNext, onError, onCompleted); + }; + + /** + * Creates an observer from a notification callback. + * + * @static + * @memberOf Observer + * @param {Function} handler Action that handles a notification. + * @returns The observer object that invokes the specified handler using a notification corresponding to each message it receives. + */ + Observer.fromNotifier = function (handler) { + return new AnonymousObserver(function (x) { + return handler(notificationCreateOnNext(x)); + }, function (exception) { + return handler(notificationCreateOnError(exception)); + }, function () { + return handler(notificationCreateOnCompleted()); + }); + }; + + /** + * Abstract base class for implementations of the Observer class. + * This base class enforces the grammar of observers where OnError and OnCompleted are terminal messages. + */ + var AbstractObserver = Rx.internals.AbstractObserver = (function (_super) { + inherits(AbstractObserver, _super); + + /** + * Creates a new observer in a non-stopped state. + * + * @constructor + */ + function AbstractObserver() { + this.isStopped = false; + _super.call(this); + } + + /** + * Notifies the observer of a new element in the sequence. + * + * @memberOf AbstractObserver + * @param {Any} value Next element in the sequence. + */ + AbstractObserver.prototype.onNext = function (value) { + if (!this.isStopped) { + this.next(value); + } + }; + + /** + * Notifies the observer that an exception has occurred. + * + * @memberOf AbstractObserver + * @param {Any} error The error that has occurred. + */ + AbstractObserver.prototype.onError = function (error) { + if (!this.isStopped) { + this.isStopped = true; + this.error(error); + } + }; + + /** + * Notifies the observer of the end of the sequence. + */ + AbstractObserver.prototype.onCompleted = function () { + if (!this.isStopped) { + this.isStopped = true; + this.completed(); + } + }; + + /** + * Disposes the observer, causing it to transition to the stopped state. + */ + AbstractObserver.prototype.dispose = function () { + this.isStopped = true; + }; + + AbstractObserver.prototype.fail = function (e) { + if (!this.isStopped) { + this.isStopped = true; + this.error(e); + return true; + } + + return false; + }; + + return AbstractObserver; + }(Observer)); + + /** + * Class to create an Observer instance from delegate-based implementations of the on* methods. + */ + var AnonymousObserver = Rx.AnonymousObserver = (function (_super) { + inherits(AnonymousObserver, _super); + + /** + * Creates an observer from the specified OnNext, OnError, and OnCompleted actions. + * @param {Any} onNext Observer's OnNext action implementation. + * @param {Any} onError Observer's OnError action implementation. + * @param {Any} onCompleted Observer's OnCompleted action implementation. + */ + function AnonymousObserver(onNext, onError, onCompleted) { + _super.call(this); + this._onNext = onNext; + this._onError = onError; + this._onCompleted = onCompleted; + } + + /** + * Calls the onNext action. + * @param {Any} value Next element in the sequence. + */ + AnonymousObserver.prototype.next = function (value) { + this._onNext(value); + }; + + /** + * Calls the onError action. + * @param {Any} error The error that has occurred. + */ + AnonymousObserver.prototype.error = function (exception) { + this._onError(exception); + }; + + /** + * Calls the onCompleted action. + */ + AnonymousObserver.prototype.completed = function () { + this._onCompleted(); + }; + + return AnonymousObserver; + }(AbstractObserver)); + + var observableProto; + + /** + * Represents a push-style collection. + */ + var Observable = Rx.Observable = (function () { + + function Observable(subscribe) { + this._subscribe = subscribe; + } + + observableProto = Observable.prototype; + + /** + * Subscribes an observer to the observable sequence. + * + * @example + * 1 - source.subscribe(); + * 2 - source.subscribe(observer); + * 3 - source.subscribe(function (x) { console.log(x); }); + * 4 - source.subscribe(function (x) { console.log(x); }, function (err) { console.log(err); }); + * 5 - source.subscribe(function (x) { console.log(x); }, function (err) { console.log(err); }, function () { console.log('done'); }); + * @param {Mixed} [observerOrOnNext] The object that is to receive notifications or an action to invoke for each element in the observable sequence. + * @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence. + * @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence. + * @returns {Diposable} The source sequence whose subscriptions and unsubscriptions happen on the specified scheduler. + */ + observableProto.subscribe = observableProto.forEach = function (observerOrOnNext, onError, onCompleted) { + var subscriber = typeof observerOrOnNext === 'object' ? + observerOrOnNext : + observerCreate(observerOrOnNext, onError, onCompleted); + + return this._subscribe(subscriber); + }; + + return Observable; + })(); + + var ScheduledObserver = Rx.internals.ScheduledObserver = (function (_super) { + inherits(ScheduledObserver, _super); + + function ScheduledObserver(scheduler, observer) { + _super.call(this); + this.scheduler = scheduler; + this.observer = observer; + this.isAcquired = false; + this.hasFaulted = false; + this.queue = []; + this.disposable = new SerialDisposable(); + } + + ScheduledObserver.prototype.next = function (value) { + var self = this; + this.queue.push(function () { + self.observer.onNext(value); + }); + }; + + ScheduledObserver.prototype.error = function (exception) { + var self = this; + this.queue.push(function () { + self.observer.onError(exception); + }); + }; + + ScheduledObserver.prototype.completed = function () { + var self = this; + this.queue.push(function () { + self.observer.onCompleted(); + }); + }; + + ScheduledObserver.prototype.ensureActive = function () { + var isOwner = false, parent = this; + if (!this.hasFaulted && this.queue.length > 0) { + isOwner = !this.isAcquired; + this.isAcquired = true; + } + if (isOwner) { + this.disposable.setDisposable(this.scheduler.scheduleRecursive(function (self) { + var work; + if (parent.queue.length > 0) { + work = parent.queue.shift(); + } else { + parent.isAcquired = false; + return; + } + try { + work(); + } catch (ex) { + parent.queue = []; + parent.hasFaulted = true; + throw ex; + } + self(); + })); + } + }; + + ScheduledObserver.prototype.dispose = function () { + _super.prototype.dispose.call(this); + this.disposable.dispose(); + }; + + return ScheduledObserver; + }(AbstractObserver)); + + /** + * Creates a list from an observable sequence. + * @returns An observable sequence containing a single element with a list containing all the elements of the source sequence. + */ + observableProto.toArray = function () { + var self = this; + return new AnonymousObservable(function(observer) { + var arr = []; + return self.subscribe( + arr.push.bind(arr), + observer.onError.bind(observer), + function () { + observer.onNext(arr); + observer.onCompleted(); + }); + }); + }; + + /** + * Creates an observable sequence from a specified subscribe method implementation. + * + * @example + * var res = Rx.Observable.create(function (observer) { return function () { } ); + * var res = Rx.Observable.create(function (observer) { return Rx.Disposable.empty; } ); + * var res = Rx.Observable.create(function (observer) { } ); + * + * @param {Function} subscribe Implementation of the resulting observable sequence's subscribe method, returning a function that will be wrapped in a Disposable. + * @returns {Observable} The observable sequence with the specified implementation for the Subscribe method. + */ + Observable.create = Observable.createWithDisposable = function (subscribe) { + return new AnonymousObservable(subscribe); + }; + + /** + * Returns an observable sequence that invokes the specified factory function whenever a new observer subscribes. + * + * @example + * var res = Rx.Observable.defer(function () { return Rx.Observable.fromArray([1,2,3]); }); + * @param {Function} observableFactory Observable factory function to invoke for each observer that subscribes to the resulting sequence or Promise. + * @returns {Observable} An observable sequence whose observers trigger an invocation of the given observable factory function. + */ + var observableDefer = Observable.defer = function (observableFactory) { + return new AnonymousObservable(function (observer) { + var result; + try { + result = observableFactory(); + } catch (e) { + return observableThrow(e).subscribe(observer); + } + isPromise(result) && (result = observableFromPromise(result)); + return result.subscribe(observer); + }); + }; + + /** + * Returns an empty observable sequence, using the specified scheduler to send out the single OnCompleted message. + * + * @example + * var res = Rx.Observable.empty(); + * var res = Rx.Observable.empty(Rx.Scheduler.timeout); + * @param {Scheduler} [scheduler] Scheduler to send the termination call on. + * @returns {Observable} An observable sequence with no elements. + */ + var observableEmpty = Observable.empty = function (scheduler) { + scheduler || (scheduler = immediateScheduler); + return new AnonymousObservable(function (observer) { + return scheduler.schedule(function () { + observer.onCompleted(); + }); + }); + }; + + /** + * Converts an array to an observable sequence, using an optional scheduler to enumerate the array. + * + * @example + * var res = Rx.Observable.fromArray([1,2,3]); + * var res = Rx.Observable.fromArray([1,2,3], Rx.Scheduler.timeout); + * @param {Scheduler} [scheduler] Scheduler to run the enumeration of the input sequence on. + * @returns {Observable} The observable sequence whose elements are pulled from the given enumerable sequence. + */ + var observableFromArray = Observable.fromArray = function (array, scheduler) { + scheduler || (scheduler = currentThreadScheduler); + return new AnonymousObservable(function (observer) { + var count = 0, len = array.length; + return scheduler.scheduleRecursive(function (self) { + if (count < len) { + observer.onNext(array[count++]); + self(); + } else { + observer.onCompleted(); + } + }); + }); + }; + + /** + * Converts an iterable into an Observable sequence + * + * @example + * var res = Rx.Observable.fromIterable(new Map()); + * var res = Rx.Observable.fromIterable(new Set(), Rx.Scheduler.timeout); + * @param {Scheduler} [scheduler] Scheduler to run the enumeration of the input sequence on. + * @returns {Observable} The observable sequence whose elements are pulled from the given generator sequence. + */ + Observable.fromIterable = function (iterable, scheduler) { + scheduler || (scheduler = currentThreadScheduler); + return new AnonymousObservable(function (observer) { + var iterator; + try { + iterator = iterable[$iterator$](); + } catch (e) { + observer.onError(e); + return; + } + + return scheduler.scheduleRecursive(function (self) { + var next; + try { + next = iterator.next(); + } catch (err) { + observer.onError(err); + return; + } + + if (next.done) { + observer.onCompleted(); + } else { + observer.onNext(next.value); + self(); + } + }); + }); + }; + + /** + * 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) { + scheduler || (scheduler = currentThreadScheduler); + return new AnonymousObservable(function (observer) { + var first = true, state = initialState; + return scheduler.scheduleRecursive(function (self) { + var hasResult, result; + try { + if (first) { + first = false; + } else { + state = iterate(state); + } + hasResult = condition(state); + if (hasResult) { + result = resultSelector(state); + } + } catch (exception) { + observer.onError(exception); + return; + } + if (hasResult) { + observer.onNext(result); + self(); + } else { + observer.onCompleted(); + } + }); + }); + }; + + /** + * Returns a non-terminating observable sequence, which can be used to denote an infinite duration (e.g. when using reactive joins). + * @returns {Observable} An observable sequence whose observers will never get called. + */ + var observableNever = Observable.never = function () { + return new AnonymousObservable(function () { + return disposableEmpty; + }); + }; + + /** + * This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments. + * @example + * var res = Rx.Observable.of(1,2,3); + * @returns {Observable} The observable sequence whose elements are pulled from the given arguments. + */ + Observable.of = function () { + var len = arguments.length, args = new Array(len); + for(var i = 0; i < len; i++) { args[i] = arguments[i]; } + return observableFromArray(args); + }; + + /** + * This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments. + * @example + * var res = Rx.Observable.of(1,2,3); + * @param {Scheduler} scheduler A scheduler to use for scheduling the arguments. + * @returns {Observable} The observable sequence whose elements are pulled from the given arguments. + */ + var observableOf = Observable.ofWithScheduler = function (scheduler) { + var len = arguments.length - 1, args = new Array(len); + for(var i = 0; i < len; i++) { args[i] = arguments[i + 1]; } + return observableFromArray(args, scheduler); + }; + + /** + * Generates an observable sequence of integral numbers within a specified range, using the specified scheduler to send out observer messages. + * + * @example + * var res = Rx.Observable.range(0, 10); + * var res = Rx.Observable.range(0, 10, Rx.Scheduler.timeout); + * @param {Number} start The value of the first integer in the sequence. + * @param {Number} count The number of sequential integers to generate. + * @param {Scheduler} [scheduler] Scheduler to run the generator loop on. If not specified, defaults to Scheduler.currentThread. + * @returns {Observable} An observable sequence that contains a range of sequential integral numbers. + */ + Observable.range = function (start, count, scheduler) { + scheduler || (scheduler = currentThreadScheduler); + return new AnonymousObservable(function (observer) { + return scheduler.scheduleRecursiveWithState(0, function (i, self) { + if (i < count) { + observer.onNext(start + i); + self(i + 1); + } else { + observer.onCompleted(); + } + }); + }); + }; + + /** + * Generates an observable sequence that repeats the given element the specified number of times, using the specified scheduler to send out observer messages. + * + * @example + * var res = Rx.Observable.repeat(42); + * var res = Rx.Observable.repeat(42, 4); + * 3 - res = Rx.Observable.repeat(42, 4, Rx.Scheduler.timeout); + * 4 - res = Rx.Observable.repeat(42, null, Rx.Scheduler.timeout); + * @param {Mixed} value Element to repeat. + * @param {Number} repeatCount [Optiona] Number of times to repeat the element. If not specified, repeats indefinitely. + * @param {Scheduler} scheduler Scheduler to run the producer loop on. If not specified, defaults to Scheduler.immediate. + * @returns {Observable} An observable sequence that repeats the given element the specified number of times. + */ + Observable.repeat = function (value, repeatCount, scheduler) { + scheduler || (scheduler = currentThreadScheduler); + if (repeatCount == null) { + repeatCount = -1; + } + return observableReturn(value, scheduler).repeat(repeatCount); + }; + + /** + * Returns an observable sequence that contains a single element, using the specified scheduler to send out observer messages. + * There is an alias called 'just', and 'returnValue' for browsers 0) { + s = q.shift(); + subscribe(s); + } else { + activeCount--; + if (isStopped && activeCount === 0) { + observer.onCompleted(); + } + } + })); + }; + group.add(sources.subscribe(function (innerSource) { + if (activeCount < maxConcurrentOrOther) { + activeCount++; + subscribe(innerSource); + } else { + q.push(innerSource); + } + }, observer.onError.bind(observer), function () { + isStopped = true; + if (activeCount === 0) { + observer.onCompleted(); + } + })); + return group; + }); + }; + + /** + * Merges all the observable sequences into a single observable sequence. + * The scheduler is optional and if not specified, the immediate scheduler is used. + * + * @example + * 1 - merged = Rx.Observable.merge(xs, ys, zs); + * 2 - merged = Rx.Observable.merge([xs, ys, zs]); + * 3 - merged = Rx.Observable.merge(scheduler, xs, ys, zs); + * 4 - merged = Rx.Observable.merge(scheduler, [xs, ys, zs]); + * @returns {Observable} The observable sequence that merges the elements of the observable sequences. + */ + var observableMerge = Observable.merge = function () { + var scheduler, sources; + if (!arguments[0]) { + scheduler = immediateScheduler; + sources = slice.call(arguments, 1); + } else if (arguments[0].now) { + scheduler = arguments[0]; + sources = slice.call(arguments, 1); + } else { + scheduler = immediateScheduler; + sources = slice.call(arguments, 0); + } + if (Array.isArray(sources[0])) { + sources = sources[0]; + } + return observableFromArray(sources, scheduler).mergeObservable(); + }; + + /** + * Merges an observable sequence of observable sequences into an observable sequence. + * @returns {Observable} The observable sequence that merges the elements of the inner sequences. + */ + observableProto.mergeObservable = observableProto.mergeAll =function () { + var sources = this; + return new AnonymousObservable(function (observer) { + var group = new CompositeDisposable(), + isStopped = false, + m = new SingleAssignmentDisposable(); + + group.add(m); + m.setDisposable(sources.subscribe(function (innerSource) { + var innerSubscription = new SingleAssignmentDisposable(); + group.add(innerSubscription); + + // Check if Promise or Observable + if (isPromise(innerSource)) { + innerSource = observableFromPromise(innerSource); + } + + innerSubscription.setDisposable(innerSource.subscribe(function (x) { + observer.onNext(x); + }, observer.onError.bind(observer), function () { + group.remove(innerSubscription); + if (isStopped && group.length === 1) { observer.onCompleted(); } + })); + }, observer.onError.bind(observer), function () { + isStopped = true; + if (group.length === 1) { observer.onCompleted(); } + })); + return group; + }); + }; + + /** + * Returns the values from the source observable sequence only after the other observable sequence produces a value. + * @param {Observable | Promise} other The observable sequence or Promise that triggers propagation of elements of the source sequence. + * @returns {Observable} An observable sequence containing the elements of the source sequence starting from the point the other sequence triggered propagation. + */ + observableProto.skipUntil = function (other) { + var source = this; + return new AnonymousObservable(function (observer) { + var isOpen = false; + var disposables = new CompositeDisposable(source.subscribe(function (left) { + isOpen && observer.onNext(left); + }, observer.onError.bind(observer), function () { + isOpen && observer.onCompleted(); + })); + + isPromise(other) && (other = observableFromPromise(other)); + + var rightSubscription = new SingleAssignmentDisposable(); + disposables.add(rightSubscription); + rightSubscription.setDisposable(other.subscribe(function () { + isOpen = true; + rightSubscription.dispose(); + }, observer.onError.bind(observer), function () { + rightSubscription.dispose(); + })); + + return disposables; + }); + }; + + /** + * Transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence. + * @returns {Observable} The observable sequence that at any point in time produces the elements of the most recent inner observable sequence that has been received. + */ + observableProto['switch'] = observableProto.switchLatest = function () { + var sources = this; + return new AnonymousObservable(function (observer) { + var hasLatest = false, + innerSubscription = new SerialDisposable(), + isStopped = false, + latest = 0, + subscription = sources.subscribe(function (innerSource) { + var d = new SingleAssignmentDisposable(), id = ++latest; + hasLatest = true; + innerSubscription.setDisposable(d); + + // Check if Promise or Observable + if (isPromise(innerSource)) { + innerSource = observableFromPromise(innerSource); + } + + d.setDisposable(innerSource.subscribe(function (x) { + if (latest === id) { + observer.onNext(x); + } + }, function (e) { + if (latest === id) { + observer.onError(e); + } + }, function () { + if (latest === id) { + hasLatest = false; + if (isStopped) { + observer.onCompleted(); + } + } + })); + }, observer.onError.bind(observer), function () { + isStopped = true; + if (!hasLatest) { + observer.onCompleted(); + } + }); + return new CompositeDisposable(subscription, innerSubscription); + }); + }; + + /** + * Returns the values from the source observable sequence until the other observable sequence produces a value. + * @param {Observable | Promise} other Observable sequence or Promise that terminates propagation of elements of the source sequence. + * @returns {Observable} An observable sequence containing the elements of the source sequence up to the point the other sequence interrupted further propagation. + */ + observableProto.takeUntil = function (other) { + var source = this; + return new AnonymousObservable(function (observer) { + isPromise(other) && (other = observableFromPromise(other)); + return new CompositeDisposable( + source.subscribe(observer), + other.subscribe(observer.onCompleted.bind(observer), observer.onError.bind(observer), noop) + ); + }); + }; + + function zipArray(second, resultSelector) { + var first = this; + return new AnonymousObservable(function (observer) { + var index = 0, len = second.length; + return first.subscribe(function (left) { + if (index < len) { + var right = second[index++], result; + try { + result = resultSelector(left, right); + } catch (e) { + observer.onError(e); + return; + } + observer.onNext(result); + } else { + observer.onCompleted(); + } + }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); + }); + } + + /** + * Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences or an array have produced an element at a corresponding index. + * The last element in the arguments must be a function to invoke for each series of elements at corresponding indexes in the sources. + * + * @example + * 1 - res = obs1.zip(obs2, fn); + * 1 - res = x1.zip([1,2,3], fn); + * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + observableProto.zip = function () { + if (Array.isArray(arguments[0])) { + return zipArray.apply(this, arguments); + } + var parent = this, sources = slice.call(arguments), resultSelector = sources.pop(); + sources.unshift(parent); + return new AnonymousObservable(function (observer) { + var n = sources.length, + queues = arrayInitialize(n, function () { return []; }), + isDone = arrayInitialize(n, function () { return false; }); + + function next(i) { + var res, queuedValues; + if (queues.every(function (x) { return x.length > 0; })) { + try { + queuedValues = queues.map(function (x) { return x.shift(); }); + res = resultSelector.apply(parent, queuedValues); + } catch (ex) { + observer.onError(ex); + return; + } + observer.onNext(res); + } else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) { + observer.onCompleted(); + } + }; + + function done(i) { + isDone[i] = true; + if (isDone.every(function (x) { return x; })) { + observer.onCompleted(); + } + } + + var subscriptions = new Array(n); + for (var idx = 0; idx < n; idx++) { + (function (i) { + var source = sources[i], sad = new SingleAssignmentDisposable(); + isPromise(source) && (source = observableFromPromise(source)); + sad.setDisposable(source.subscribe(function (x) { + queues[i].push(x); + next(i); + }, observer.onError.bind(observer), function () { + done(i); + })); + subscriptions[i] = sad; + })(idx); + } + + return new CompositeDisposable(subscriptions); + }); + }; + /** + * Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index. + * @param arguments Observable sources. + * @param {Function} resultSelector Function to invoke for each series of elements at corresponding indexes in the sources. + * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + Observable.zip = function () { + var args = slice.call(arguments, 0), + first = args.shift(); + return first.zip.apply(first, args); + }; + + /** + * Merges the specified observable sequences into one observable sequence by emitting a list with the elements of the observable sequences at corresponding indexes. + * @param arguments Observable sources. + * @returns {Observable} An observable sequence containing lists of elements at corresponding indexes. + */ + Observable.zipArray = function () { + var sources = argsOrArray(arguments, 0); + return new AnonymousObservable(function (observer) { + var n = sources.length, + queues = arrayInitialize(n, function () { return []; }), + isDone = arrayInitialize(n, function () { return false; }); + + function next(i) { + if (queues.every(function (x) { return x.length > 0; })) { + var res = queues.map(function (x) { return x.shift(); }); + observer.onNext(res); + } else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) { + observer.onCompleted(); + return; + } + }; + + function done(i) { + isDone[i] = true; + if (isDone.every(identity)) { + observer.onCompleted(); + return; + } + } + + var subscriptions = new Array(n); + for (var idx = 0; idx < n; idx++) { + (function (i) { + subscriptions[i] = new SingleAssignmentDisposable(); + subscriptions[i].setDisposable(sources[i].subscribe(function (x) { + queues[i].push(x); + next(i); + }, observer.onError.bind(observer), function () { + done(i); + })); + })(idx); + } + + var compositeDisposable = new CompositeDisposable(subscriptions); + compositeDisposable.add(disposableCreate(function () { + for (var qIdx = 0, qLen = queues.length; qIdx < qLen; qIdx++) { + queues[qIdx] = []; + } + })); + return compositeDisposable; + }); + }; + + /** + * Hides the identity of an observable sequence. + * @returns {Observable} An observable sequence that hides the identity of the source sequence. + */ + observableProto.asObservable = function () { + var source = this; + return new AnonymousObservable(function (observer) { + return source.subscribe(observer); + }); + }; + + /** + * Dematerializes the explicit notification values of an observable sequence as implicit notifications. + * @returns {Observable} An observable sequence exhibiting the behavior corresponding to the source sequence's notification values. + */ + observableProto.dematerialize = function () { + var source = this; + return new AnonymousObservable(function (observer) { + return source.subscribe(function (x) { + return x.accept(observer); + }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); + }); + }; + + /** + * Returns an observable sequence that contains only distinct contiguous elements according to the keySelector and the comparer. + * + * var obs = observable.distinctUntilChanged(); + * var obs = observable.distinctUntilChanged(function (x) { return x.id; }); + * var obs = observable.distinctUntilChanged(function (x) { return x.id; }, function (x, y) { return x === y; }); + * + * @param {Function} [keySelector] A function to compute the comparison key for each element. If not provided, it projects the value. + * @param {Function} [comparer] Equality comparer for computed key values. If not provided, defaults to an equality comparer function. + * @returns {Observable} An observable sequence only containing the distinct contiguous elements, based on a computed key value, from the source sequence. + */ + observableProto.distinctUntilChanged = function (keySelector, comparer) { + var source = this; + keySelector || (keySelector = identity); + comparer || (comparer = defaultComparer); + return new AnonymousObservable(function (observer) { + var hasCurrentKey = false, currentKey; + return source.subscribe(function (value) { + var comparerEquals = false, key; + try { + key = keySelector(value); + } catch (exception) { + observer.onError(exception); + return; + } + if (hasCurrentKey) { + try { + comparerEquals = comparer(currentKey, key); + } catch (exception) { + observer.onError(exception); + return; + } + } + if (!hasCurrentKey || !comparerEquals) { + hasCurrentKey = true; + currentKey = key; + observer.onNext(value); + } + }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); + }); + }; + + /** + * Invokes an action for each element in the observable sequence and invokes an action upon graceful or exceptional termination of the observable sequence. + * This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline. + * + * @example + * var res = observable.doAction(observer); + * var res = observable.doAction(onNext); + * var res = observable.doAction(onNext, onError); + * var res = observable.doAction(onNext, onError, onCompleted); + * @param {Mixed} observerOrOnNext Action to invoke for each element in the observable sequence or an observer. + * @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function. + * @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function. + * @returns {Observable} The source sequence with the side-effecting behavior applied. + */ + observableProto['do'] = observableProto.doAction = function (observerOrOnNext, onError, onCompleted) { + var source = this, onNextFunc; + if (typeof observerOrOnNext === 'function') { + onNextFunc = observerOrOnNext; + } else { + onNextFunc = observerOrOnNext.onNext.bind(observerOrOnNext); + onError = observerOrOnNext.onError.bind(observerOrOnNext); + onCompleted = observerOrOnNext.onCompleted.bind(observerOrOnNext); + } + return new AnonymousObservable(function (observer) { + return source.subscribe(function (x) { + try { + onNextFunc(x); + } catch (e) { + observer.onError(e); + } + observer.onNext(x); + }, function (exception) { + if (!onError) { + observer.onError(exception); + } else { + try { + onError(exception); + } catch (e) { + observer.onError(e); + } + observer.onError(exception); + } + }, function () { + if (!onCompleted) { + observer.onCompleted(); + } else { + try { + onCompleted(); + } catch (e) { + observer.onError(e); + } + observer.onCompleted(); + } + }); + }); + }; + + /** + * Invokes a specified action after the source observable sequence terminates gracefully or exceptionally. + * + * @example + * var res = observable.finallyAction(function () { console.log('sequence ended'; }); + * @param {Function} finallyAction Action to invoke after the source observable sequence terminates. + * @returns {Observable} Source sequence with the action-invoking termination behavior applied. + */ + observableProto['finally'] = observableProto.finallyAction = function (action) { + var source = this; + return new AnonymousObservable(function (observer) { + var subscription; + try { + subscription = source.subscribe(observer); + } catch (e) { + action(); + throw e; + } + return disposableCreate(function () { + try { + subscription.dispose(); + } catch (e) { + throw e; + } finally { + action(); + } + }); + }); + }; + + /** + * Ignores all elements in an observable sequence leaving only the termination messages. + * @returns {Observable} An empty observable sequence that signals termination, successful or exceptional, of the source sequence. + */ + observableProto.ignoreElements = function () { + var source = this; + return new AnonymousObservable(function (observer) { + return source.subscribe(noop, observer.onError.bind(observer), observer.onCompleted.bind(observer)); + }); + }; + + /** + * Materializes the implicit notifications of an observable sequence as explicit notification values. + * @returns {Observable} An observable sequence containing the materialized notification values from the source sequence. + */ + observableProto.materialize = function () { + var source = this; + return new AnonymousObservable(function (observer) { + return source.subscribe(function (value) { + observer.onNext(notificationCreateOnNext(value)); + }, function (e) { + observer.onNext(notificationCreateOnError(e)); + observer.onCompleted(); + }, function () { + observer.onNext(notificationCreateOnCompleted()); + observer.onCompleted(); + }); + }); + }; + + /** + * Repeats the observable sequence a specified number of times. If the repeat count is not specified, the sequence repeats indefinitely. + * + * @example + * var res = repeated = source.repeat(); + * var res = repeated = source.repeat(42); + * @param {Number} [repeatCount] Number of times to repeat the sequence. If not provided, repeats the sequence indefinitely. + * @returns {Observable} The observable sequence producing the elements of the given sequence repeatedly. + */ + observableProto.repeat = function (repeatCount) { + return enumerableRepeat(this, repeatCount).concat(); + }; + + /** + * Repeats the source observable sequence the specified number of times or until it successfully terminates. If the retry count is not specified, it retries indefinitely. + * + * @example + * var res = retried = retry.repeat(); + * var res = retried = retry.repeat(42); + * @param {Number} [retryCount] Number of times to retry the sequence. If not provided, retry the sequence indefinitely. + * @returns {Observable} An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully. + */ + observableProto.retry = function (retryCount) { + return enumerableRepeat(this, retryCount).catchException(); + }; + + /** + * Applies an accumulator function over an observable sequence and returns each intermediate result. The optional seed value is used as the initial accumulator value. + * For aggregation behavior with no intermediate results, see Observable.aggregate. + * @example + * var res = source.scan(function (acc, x) { return acc + x; }); + * var res = source.scan(0, function (acc, x) { return acc + x; }); + * @param {Mixed} [seed] The initial accumulator value. + * @param {Function} accumulator An accumulator function to be invoked on each element. + * @returns {Observable} An observable sequence containing the accumulated values. + */ + observableProto.scan = function () { + var hasSeed = false, seed, accumulator, source = this; + if (arguments.length === 2) { + hasSeed = true; + seed = arguments[0]; + accumulator = arguments[1]; + } else { + accumulator = arguments[0]; + } + return new AnonymousObservable(function (observer) { + var hasAccumulation, accumulation, hasValue; + return source.subscribe ( + function (x) { + try { + if (!hasValue) { + hasValue = true; + } + + if (hasAccumulation) { + accumulation = accumulator(accumulation, x); + } else { + accumulation = hasSeed ? accumulator(seed, x) : x; + hasAccumulation = true; + } + } catch (e) { + observer.onError(e); + return; + } + + observer.onNext(accumulation); + }, + observer.onError.bind(observer), + function () { + if (!hasValue && hasSeed) { + observer.onNext(seed); + } + observer.onCompleted(); + } + ); + }); + }; + + /** + * Bypasses a specified number of elements at the end of an observable sequence. + * @description + * This operator accumulates a queue with a length enough to store the first `count` elements. As more elements are + * received, elements are taken from the front of the queue and produced on the result sequence. This causes elements to be delayed. + * @param count Number of elements to bypass at the end of the source sequence. + * @returns {Observable} An observable sequence containing the source sequence elements except for the bypassed ones at the end. + */ + observableProto.skipLast = function (count) { + var source = this; + return new AnonymousObservable(function (observer) { + var q = []; + return source.subscribe(function (x) { + q.push(x); + if (q.length > count) { + observer.onNext(q.shift()); + } + }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); + }); + }; + + /** + * Prepends a sequence of values to an observable sequence with an optional scheduler and an argument list of values to prepend. + * + * var res = source.startWith(1, 2, 3); + * var res = source.startWith(Rx.Scheduler.timeout, 1, 2, 3); + * + * @memberOf Observable# + * @returns {Observable} The source sequence prepended with the specified values. + */ + observableProto.startWith = function () { + var values, scheduler, start = 0; + if (!!arguments.length && 'now' in Object(arguments[0])) { + scheduler = arguments[0]; + start = 1; + } else { + scheduler = immediateScheduler; + } + values = slice.call(arguments, start); + return enumerableFor([observableFromArray(values, scheduler), this]).concat(); + }; + + /** + * Returns a specified number of contiguous elements from the end of an observable sequence, using an optional scheduler to drain the queue. + * + * @example + * var res = source.takeLast(5); + * var res = source.takeLast(5, Rx.Scheduler.timeout); + * + * @description + * This operator accumulates a buffer with a length enough to store elements count elements. Upon completion of + * the source sequence, this buffer is drained on the result sequence. This causes the elements to be delayed. + * @param {Number} count Number of elements to take from the end of the source sequence. + * @param {Scheduler} [scheduler] Scheduler used to drain the queue upon completion of the source sequence. + * @returns {Observable} An observable sequence containing the specified number of elements from the end of the source sequence. + */ + observableProto.takeLast = function (count, scheduler) { + return this.takeLastBuffer(count).selectMany(function (xs) { return observableFromArray(xs, scheduler); }); + }; + + /** + * Returns an array with the specified number of contiguous elements from the end of an observable sequence. + * + * @description + * This operator accumulates a buffer with a length enough to store count elements. Upon completion of the + * source sequence, this buffer is produced on the result sequence. + * @param {Number} count Number of elements to take from the end of the source sequence. + * @returns {Observable} An observable sequence containing a single array with the specified number of elements from the end of the source sequence. + */ + observableProto.takeLastBuffer = function (count) { + var source = this; + return new AnonymousObservable(function (observer) { + var q = []; + return source.subscribe(function (x) { + q.push(x); + if (q.length > count) { + q.shift(); + } + }, observer.onError.bind(observer), function () { + observer.onNext(q); + observer.onCompleted(); + }); + }); + }; + + function concatMap(selector) { + return this.map(function (x, i) { + var result = selector(x, i); + return isPromise(result) ? observableFromPromise(result) : result; + }).concatAll(); + } + + function concatMapObserver(onNext, onError, onCompleted) { + var source = this; + return new AnonymousObservable(function (observer) { + var index = 0; + + return source.subscribe( + function (x) { + observer.onNext(onNext(x, index++)); + }, + function (err) { + observer.onNext(onError(err)); + observer.completed(); + }, + function () { + observer.onNext(onCompleted()); + observer.onCompleted(); + }); + }).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.selectMany(function (x) { return Rx.Observable.range(0, x); }); + * Or: + * Projects each element of an observable sequence to an observable sequence, invokes the result selector for the source element and each of the corresponding inner sequence's elements, and merges the results into one observable sequence. + * + * var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); }, function (x, y) { return x + y; }); + * Or: + * Projects each element of the source observable sequence to the other observable sequence and merges the resulting observable sequences into one observable sequence. + * + * var res = source.selectMany(Rx.Observable.fromArray([1,2,3])); + * @param selector A transform function to apply to each element or an observable sequence to project each element from the + * source sequence onto which could be either an observable or Promise. + * @param {Function} [resultSelector] A transform function to apply to each element of the intermediate sequence. + * @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) { + if (resultSelector) { + return this.concatMap(function (x, i) { + var selectorResult = selector(x, i), + result = isPromise(selectorResult) ? observableFromPromise(selectorResult) : selectorResult; + + return result.map(function (y) { + return resultSelector(x, y, i); + }); + }); + } + if (typeof selector === 'function') { + return concatMap.call(this, selector); + } + return concatMap.call(this, function () { + return selector; + }); + }; + + /** + * Projects each element of an observable sequence into a new form by incorporating the element's index. + * @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element. + * @param {Any} [thisArg] Object to use as this when executing callback. + * @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source. + */ + observableProto.select = observableProto.map = function (selector, thisArg) { + var parent = this; + return new AnonymousObservable(function (observer) { + var count = 0; + return parent.subscribe(function (value) { + var result; + try { + result = selector.call(thisArg, value, count++, parent); + } catch (exception) { + observer.onError(exception); + return; + } + observer.onNext(result); + }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); + }); + }; + + /** + * Retrieves the value of a specified property from all elements in the Observable sequence. + * @param {String} property The property to pluck. + * @returns {Observable} Returns a new Observable sequence of property values. + */ + observableProto.pluck = function (property) { + return this.select(function (x) { return x[property]; }); + }; + + function selectMany(selector) { + return this.select(function (x, i) { + var result = selector(x, i); + return isPromise(result) ? observableFromPromise(result) : result; + }).mergeObservable(); + } + + function selectManyObserver(onNext, onError, onCompleted) { + var source = this; + return new AnonymousObservable(function (observer) { + var index = 0; + + return source.subscribe( + function (x) { + observer.onNext(onNext(x, index++)); + }, + function (err) { + observer.onNext(onError(err)); + observer.completed(); + }, + function () { + observer.onNext(onCompleted()); + observer.onCompleted(); + }); + }).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 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.selectMany = observableProto.flatMap = function (selector, resultSelector) { + if (resultSelector) { + return this.selectMany(function (x, i) { + var selectorResult = selector(x, i), + result = isPromise(selectorResult) ? observableFromPromise(selectorResult) : selectorResult; + + return result.select(function (y) { + return resultSelector(x, y, i); + }); + }); + } + if (typeof selector === 'function') { + return selectMany.call(this, selector); + } + return selectMany.call(this, function () { + return selector; + }); + }; + + /** + * Projects each element of an observable sequence into a new sequence of observable sequences by incorporating the element's index and then + * transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence. + * @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element. + * @param {Any} [thisArg] Object to use as this when executing callback. + * @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source producing an Observable of Observable sequences + * and that at any point in time produces the elements of the most recent inner observable sequence that has been received. + */ + observableProto.selectSwitch = observableProto.flatMapLatest = observableProto.switchMap = function (selector, thisArg) { + return this.select(selector, thisArg).switchLatest(); + }; + + /** + * Bypasses a specified number of elements in an observable sequence and then returns the remaining elements. + * @param {Number} count The number of elements to skip before returning the remaining elements. + * @returns {Observable} An observable sequence that contains the elements that occur after the specified index in the input sequence. + */ + observableProto.skip = function (count) { + if (count < 0) { + throw new Error(argumentOutOfRange); + } + var observable = this; + return new AnonymousObservable(function (observer) { + var remaining = count; + return observable.subscribe(function (x) { + if (remaining <= 0) { + observer.onNext(x); + } else { + remaining--; + } + }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); + }); + }; + + /** + * Bypasses elements in an observable sequence as long as a specified condition is true and then returns the remaining elements. + * The element's index is used in the logic of the predicate function. + * + * var res = source.skipWhile(function (value) { return value < 10; }); + * var res = source.skipWhile(function (value, index) { return value < 10 || index < 10; }); + * @param {Function} predicate A function to test each element for a condition; the second parameter of the function represents the index of the source element. + * @param {Any} [thisArg] Object to use as this when executing callback. + * @returns {Observable} An observable sequence that contains the elements from the input sequence starting at the first element in the linear series that does not pass the test specified by predicate. + */ + observableProto.skipWhile = function (predicate, thisArg) { + var source = this; + return new AnonymousObservable(function (observer) { + var i = 0, running = false; + return source.subscribe(function (x) { + if (!running) { + try { + running = !predicate.call(thisArg, x, i++, source); + } catch (e) { + observer.onError(e); + return; + } + } + if (running) { + observer.onNext(x); + } + }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); + }); + }; + + /** + * Returns a specified number of contiguous elements from the start of an observable sequence, using the specified scheduler for the edge case of take(0). + * + * var res = source.take(5); + * var res = source.take(0, Rx.Scheduler.timeout); + * @param {Number} count The number of elements to return. + * @param {Scheduler} [scheduler] Scheduler used to produce an OnCompleted message in case 0) { + now = scheduler.now(); + d = d + p; + if (d <= now) { + d = now + p; + } + } + observer.onNext(count++); + self(d); + }); + }); + } + + /** + * 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) { + scheduler || (scheduler = timeoutScheduler); + return observableTimerTimeSpanAndPeriod(period, period, scheduler); + }; + + /** + * Returns an observable sequence that produces a value after dueTime has elapsed and then after each period. + * + * @example + * var res = Rx.Observable.timer(5000); + * var res = Rx.Observable.timer(5000, 1000); + * var res = Rx.Observable.timer(5000, Rx.Scheduler.timeout); + * var res = Rx.Observable.timer(5000, 1000, Rx.Scheduler.timeout); + * + * @param {Number} dueTime 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; + scheduler || (scheduler = timeoutScheduler); + if (typeof periodOrScheduler === 'number') { + period = periodOrScheduler; + } else if (typeof periodOrScheduler === 'object' && 'now' in periodOrScheduler) { + scheduler = periodOrScheduler; + } + return period === undefined ? + observableTimerTimeSpan(dueTime, scheduler) : + observableTimerTimeSpanAndPeriod(dueTime, period, scheduler); + }; + + /** + * Time shifts the observable sequence by dueTime. The relative time intervals between the values are preserved. + * + * @example + * var res = Rx.Observable.delay(5000); + * var 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) { + scheduler || (scheduler = timeoutScheduler); + var source = this; + 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); + }); + }; + + /** + * Ignores values from an observable sequence which are followed by another value before dueTime. + * + * @example + * 1 - res = source.throttle(5000); // 5 seconds + * 2 - res = source.throttle(5000, scheduler); + * + * @param {Number} dueTime Duration of the throttle period for each value (specified as an integer denoting milliseconds). + * @param {Scheduler} [scheduler] Scheduler to run the throttle timers on. If not specified, the timeout scheduler is used. + * @returns {Observable} The throttled sequence. + */ + observableProto.throttle = function (dueTime, scheduler) { + scheduler || (scheduler = timeoutScheduler); + var source = this; + return this.throttleWithSelector(function () { return observableTimer(dueTime, scheduler); }) + }; + + /** + * 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; + scheduler || (scheduler = timeoutScheduler); + return observableDefer(function () { + var last = scheduler.now(); + return source.select(function (x) { + var now = scheduler.now(), span = now - last; + last = now; + return { + value: x, + interval: span + }; + }); + }); + }; + + /** + * Records the timestamp for each value in an observable sequence. + * + * @example + * 1 - res = source.timestamp(); // produces { value: x, timestamp: ts } + * 2 - res = source.timestamp(Rx.Scheduler.timeout); + * + * @param {Scheduler} [scheduler] Scheduler used to compute timestamps. If not specified, the timeout scheduler is used. + * @returns {Observable} An observable sequence with timestamp information on values. + */ + observableProto.timestamp = function (scheduler) { + scheduler || (scheduler = timeoutScheduler); + return this.select(function (x) { + return { + value: x, + timestamp: scheduler.now() + }; + }); + }; + + function sampleObservable(source, sampler) { + + return new AnonymousObservable(function (observer) { + var atEnd, value, hasValue; + + function sampleSubscribe() { + if (hasValue) { + hasValue = false; + observer.onNext(value); + } + if (atEnd) { + observer.onCompleted(); + } + } + + return new CompositeDisposable( + source.subscribe(function (newValue) { + hasValue = true; + value = newValue; + }, observer.onError.bind(observer), function () { + atEnd = true; + }), + sampler.subscribe(sampleSubscribe, observer.onError.bind(observer), sampleSubscribe) + ); + }); + } + + /** + * Samples the observable sequence at each interval. + * + * @example + * 1 - res = source.sample(sampleObservable); // Sampler tick sequence + * 2 - res = source.sample(5000); // 5 seconds + * 2 - res = source.sample(5000, Rx.Scheduler.timeout); // 5 seconds + * + * @param {Mixed} intervalOrSampler Interval at which to sample (specified as an integer denoting milliseconds) or Sampler Observable. + * @param {Scheduler} [scheduler] Scheduler to run the sampling timer on. If not specified, the timeout scheduler is used. + * @returns {Observable} Sampled observable sequence. + */ + observableProto.sample = function (intervalOrSampler, scheduler) { + scheduler || (scheduler = timeoutScheduler); + if (typeof intervalOrSampler === 'number') { + return sampleObservable(this, observableinterval(intervalOrSampler, scheduler)); + } + return sampleObservable(this, intervalOrSampler); + }; + + /** + * Returns the source observable sequence or the other observable sequence if dueTime elapses. + * + * @example + * 1 - res = source.timeout(new Date()); // As a date + * 2 - res = source.timeout(5000); // 5 seconds + * 3 - res = source.timeout(new Date(), Rx.Observable.returnValue(42)); // As a date and timeout observable + * 4 - res = source.timeout(5000, Rx.Observable.returnValue(42)); // 5 seconds and timeout observable + * 5 - res = source.timeout(new Date(), Rx.Observable.returnValue(42), Rx.Scheduler.timeout); // As a date and timeout observable + * 6 - res = source.timeout(5000, Rx.Observable.returnValue(42), Rx.Scheduler.timeout); // 5 seconds and timeout observable + * + * @param {Number} dueTime Absolute (specified as a Date object) or relative time (specified as an integer denoting milliseconds) when a timeout occurs. + * @param {Observable} [other] Sequence to return in case of a timeout. If not specified, a timeout error throwing sequence will be used. + * @param {Scheduler} [scheduler] Scheduler to run the timeout timers on. If not specified, the timeout scheduler is used. + * @returns {Observable} The source sequence switching to the other sequence in case of a timeout. + */ + observableProto.timeout = function (dueTime, other, scheduler) { + other || (other = observableThrow(new Error('Timeout'))); + scheduler || (scheduler = timeoutScheduler); + + var source = this, schedulerMethod = dueTime instanceof Date ? + 'scheduleWithAbsolute' : + 'scheduleWithRelative'; + + return new AnonymousObservable(function (observer) { + var id = 0, + original = new SingleAssignmentDisposable(), + subscription = new SerialDisposable(), + switched = false, + timer = new SerialDisposable(); + + subscription.setDisposable(original); + + var createTimer = function () { + var myId = id; + timer.setDisposable(scheduler[schedulerMethod](dueTime, function () { + if (id === myId) { + isPromise(other) && (other = observableFromPromise(other)); + subscription.setDisposable(other.subscribe(observer)); + } + })); + }; + + createTimer(); + + original.setDisposable(source.subscribe(function (x) { + if (!switched) { + id++; + observer.onNext(x); + createTimer(); + } + }, function (e) { + if (!switched) { + id++; + observer.onError(e); + } + }, function () { + if (!switched) { + id++; + observer.onCompleted(); + } + })); + return new CompositeDisposable(subscription, timer); + }); + }; + + /** + * Generates an observable sequence by iterating a state from an initial state until the condition fails. + * + * @example + * res = source.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) { + scheduler || (scheduler = timeoutScheduler); + return new AnonymousObservable(function (observer) { + var first = true, + hasResult = false, + result, + state = initialState, + time; + return scheduler.scheduleRecursiveWithRelative(0, function (self) { + if (hasResult) { + observer.onNext(result); + } + try { + if (first) { + first = false; + } else { + state = iterate(state); + } + hasResult = condition(state); + if (hasResult) { + result = resultSelector(state); + time = timeSelector(state); + } + } catch (e) { + observer.onError(e); + return; + } + if (hasResult) { + self(time); + } else { + observer.onCompleted(); + } + }); + }); + }; + + /** + * Time shifts the observable sequence by delaying the subscription. + * + * @example + * 1 - res = source.delaySubscription(5000); // 5s + * 2 - res = source.delaySubscription(5000, Rx.Scheduler.timeout); // 5 seconds + * + * @param {Number} dueTime Absolute or relative time to perform the subscription at. + * @param {Scheduler} [scheduler] Scheduler to run the subscription delay timer on. If not specified, the timeout scheduler is used. + * @returns {Observable} Time-shifted sequence. + */ + observableProto.delaySubscription = function (dueTime, scheduler) { + scheduler || (scheduler = timeoutScheduler); + return this.delayWithSelector(observableTimer(dueTime, scheduler), function () { return observableEmpty(); }); + }; + + /** + * Time shifts the observable sequence based on a subscription delay and a delay selector function for each element. + * + * @example + * 1 - res = source.delayWithSelector(function (x) { return Rx.Scheduler.timer(5000); }); // with selector only + * 1 - res = source.delayWithSelector(Rx.Observable.timer(2000), function (x) { return Rx.Observable.timer(x); }); // with delay and selector + * + * @param {Observable} [subscriptionDelay] Sequence indicating the delay for the subscription to the source. + * @param {Function} delayDurationSelector Selector function to retrieve a sequence indicating the delay for each given element. + * @returns {Observable} Time-shifted sequence. + */ + observableProto.delayWithSelector = function (subscriptionDelay, delayDurationSelector) { + var source = this, subDelay, selector; + if (typeof subscriptionDelay === 'function') { + selector = subscriptionDelay; + } else { + subDelay = subscriptionDelay; + selector = delayDurationSelector; + } + return new AnonymousObservable(function (observer) { + var delays = new CompositeDisposable(), atEnd = false, done = function () { + if (atEnd && delays.length === 0) { + observer.onCompleted(); + } + }, subscription = new SerialDisposable(), start = function () { + subscription.setDisposable(source.subscribe(function (x) { + var delay; + try { + delay = selector(x); + } catch (error) { + observer.onError(error); + return; + } + var d = new SingleAssignmentDisposable(); + delays.add(d); + d.setDisposable(delay.subscribe(function () { + observer.onNext(x); + delays.remove(d); + done(); + }, observer.onError.bind(observer), function () { + observer.onNext(x); + delays.remove(d); + done(); + })); + }, observer.onError.bind(observer), function () { + atEnd = true; + subscription.dispose(); + done(); + })); + }; + + if (!subDelay) { + start(); + } else { + subscription.setDisposable(subDelay.subscribe(function () { + start(); + }, observer.onError.bind(observer), function () { start(); })); + } + + return new CompositeDisposable(subscription, delays); + }); + }; + + /** + * Returns the source observable sequence, switching to the other observable sequence if a timeout is signaled. + * + * @example + * 1 - res = source.timeoutWithSelector(Rx.Observable.timer(500)); + * 2 - res = source.timeoutWithSelector(Rx.Observable.timer(500), function (x) { return Rx.Observable.timer(200); }); + * 3 - res = source.timeoutWithSelector(Rx.Observable.timer(500), function (x) { return Rx.Observable.timer(200); }, Rx.Observable.returnValue(42)); + * + * @param {Observable} [firstTimeout] Observable sequence that represents the timeout for the first element. If not provided, this defaults to Observable.never(). + * @param {Function} [timeoutDurationSelector] Selector to retrieve an observable sequence that represents the timeout between the current element and the next element. + * @param {Observable} [other] Sequence to return in case of a timeout. If not provided, this is set to Observable.throwException(). + * @returns {Observable} The source sequence switching to the other sequence in case of a timeout. + */ + observableProto.timeoutWithSelector = function (firstTimeout, timeoutdurationSelector, other) { + if (arguments.length === 1) { + timeoutdurationSelector = firstTimeout; + var firstTimeout = observableNever(); + } + other || (other = observableThrow(new Error('Timeout'))); + var source = this; + return new AnonymousObservable(function (observer) { + var subscription = new SerialDisposable(), timer = new SerialDisposable(), original = new SingleAssignmentDisposable(); + + subscription.setDisposable(original); + + var id = 0, switched = false, setTimer = function (timeout) { + var myId = id, timerWins = function () { + return id === myId; + }; + var d = new SingleAssignmentDisposable(); + timer.setDisposable(d); + d.setDisposable(timeout.subscribe(function () { + if (timerWins()) { + subscription.setDisposable(other.subscribe(observer)); + } + d.dispose(); + }, function (e) { + if (timerWins()) { + observer.onError(e); + } + }, function () { + if (timerWins()) { + subscription.setDisposable(other.subscribe(observer)); + } + })); + }; + + setTimer(firstTimeout); + var observerWins = function () { + var res = !switched; + if (res) { + id++; + } + return res; + }; + + original.setDisposable(source.subscribe(function (x) { + if (observerWins()) { + observer.onNext(x); + var timeout; + try { + timeout = timeoutdurationSelector(x); + } catch (e) { + observer.onError(e); + return; + } + setTimer(timeout); + } + }, function (e) { + if (observerWins()) { + observer.onError(e); + } + }, function () { + if (observerWins()) { + observer.onCompleted(); + } + })); + return new CompositeDisposable(subscription, timer); + }); + }; + + /** + * Ignores values from an observable sequence which are followed by another value within a computed throttle duration. + * + * @example + * 1 - res = source.delayWithSelector(function (x) { return Rx.Scheduler.timer(x + x); }); + * + * @param {Function} throttleDurationSelector Selector function to retrieve a sequence indicating the throttle duration for each given element. + * @returns {Observable} The throttled sequence. + */ + observableProto.throttleWithSelector = function (throttleDurationSelector) { + var source = this; + return new AnonymousObservable(function (observer) { + var value, hasValue = false, cancelable = new SerialDisposable(), id = 0, subscription = source.subscribe(function (x) { + var throttle; + try { + throttle = throttleDurationSelector(x); + } catch (e) { + observer.onError(e); + return; + } + hasValue = true; + value = x; + id++; + var currentid = id, d = new SingleAssignmentDisposable(); + cancelable.setDisposable(d); + d.setDisposable(throttle.subscribe(function () { + if (hasValue && id === currentid) { + observer.onNext(value); + } + hasValue = false; + d.dispose(); + }, observer.onError.bind(observer), function () { + if (hasValue && id === currentid) { + observer.onNext(value); + } + hasValue = false; + d.dispose(); + })); + }, function (e) { + cancelable.dispose(); + observer.onError(e); + hasValue = false; + id++; + }, function () { + cancelable.dispose(); + if (hasValue) { + observer.onNext(value); + } + observer.onCompleted(); + hasValue = false; + id++; + }); + return new CompositeDisposable(subscription, cancelable); + }); + }; + + /** + * Skips elements for the specified duration from the end of the observable source sequence, using the specified scheduler to run timers. + * + * 1 - res = source.skipLastWithTime(5000); + * 2 - res = source.skipLastWithTime(5000, scheduler); + * + * @description + * This operator accumulates a queue with a length enough to store elements received during the initial duration window. + * As more elements are received, elements older than the specified duration are taken from the queue and produced on the + * result sequence. This causes elements to be delayed with duration. + * @param {Number} duration Duration for skipping elements from the end of the sequence. + * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout + * @returns {Observable} An observable sequence with the elements skipped during the specified duration from the end of the source sequence. + */ + observableProto.skipLastWithTime = function (duration, scheduler) { + scheduler || (scheduler = timeoutScheduler); + var source = this; + return new AnonymousObservable(function (observer) { + var q = []; + return source.subscribe(function (x) { + var now = scheduler.now(); + q.push({ interval: now, value: x }); + while (q.length > 0 && now - q[0].interval >= duration) { + observer.onNext(q.shift().value); + } + }, observer.onError.bind(observer), function () { + var now = scheduler.now(); + while (q.length > 0 && now - q[0].interval >= duration) { + observer.onNext(q.shift().value); + } + observer.onCompleted(); + }); + }); + }; + + /** + * Returns elements within the specified duration from the end of the observable source sequence, using the specified schedulers to run timers and to drain the collected elements. + * + * @example + * 1 - res = source.takeLastWithTime(5000, [optional timer scheduler], [optional loop scheduler]); + * @description + * This operator accumulates a queue with a length enough to store elements received during the initial duration window. + * As more elements are received, elements older than the specified duration are taken from the queue and produced on the + * result sequence. This causes elements to be delayed with duration. + * @param {Number} duration Duration for taking elements from the end of the sequence. + * @param {Scheduler} [timerScheduler] Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. + * @param {Scheduler} [loopScheduler] Scheduler to drain the collected elements. If not specified, defaults to Rx.Scheduler.immediate. + * @returns {Observable} An observable sequence with the elements taken during the specified duration from the end of the source sequence. + */ + observableProto.takeLastWithTime = function (duration, timerScheduler, loopScheduler) { + return this.takeLastBufferWithTime(duration, timerScheduler).selectMany(function (xs) { return observableFromArray(xs, loopScheduler); }); + }; + + /** + * Returns an array with the elements within the specified duration from the end of the observable source sequence, using the specified scheduler to run timers. + * + * @example + * 1 - res = source.takeLastBufferWithTime(5000, [optional scheduler]); + * @description + * This operator accumulates a queue with a length enough to store elements received during the initial duration window. + * As more elements are received, elements older than the specified duration are taken from the queue and produced on the + * result sequence. This causes elements to be delayed with duration. + * @param {Number} duration Duration for taking elements from the end of the sequence. + * @param {Scheduler} scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. + * @returns {Observable} An observable sequence containing a single array with the elements taken during the specified duration from the end of the source sequence. + */ + observableProto.takeLastBufferWithTime = function (duration, scheduler) { + var source = this; + scheduler || (scheduler = timeoutScheduler); + return new AnonymousObservable(function (observer) { + var q = []; + + return source.subscribe(function (x) { + var now = scheduler.now(); + q.push({ interval: now, value: x }); + while (q.length > 0 && now - q[0].interval >= duration) { + q.shift(); + } + }, observer.onError.bind(observer), function () { + var now = scheduler.now(), res = []; + while (q.length > 0) { + var next = q.shift(); + if (now - next.interval <= duration) { + res.push(next.value); + } + } + + observer.onNext(res); + observer.onCompleted(); + }); + }); + }; + + /** + * Takes elements for the specified duration from the start of the observable source sequence, using the specified scheduler to run timers. + * + * @example + * 1 - res = source.takeWithTime(5000, [optional scheduler]); + * @description + * This operator accumulates a queue with a length enough to store elements received during the initial duration window. + * As more elements are received, elements older than the specified duration are taken from the queue and produced on the + * result sequence. This causes elements to be delayed with duration. + * @param {Number} duration Duration for taking elements from the start of the sequence. + * @param {Scheduler} scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. + * @returns {Observable} An observable sequence with the elements taken during the specified duration from the start of the source sequence. + */ + observableProto.takeWithTime = function (duration, scheduler) { + var source = this; + scheduler || (scheduler = timeoutScheduler); + return new AnonymousObservable(function (observer) { + var t = scheduler.scheduleWithRelative(duration, function () { + observer.onCompleted(); + }); + + return new CompositeDisposable(t, source.subscribe(observer)); + }); + }; + + /** + * Skips elements for the specified duration from the start of the observable source sequence, using the specified scheduler to run timers. + * + * @example + * 1 - res = source.skipWithTime(5000, [optional scheduler]); + * + * @description + * Specifying a zero value for duration doesn't guarantee no elements will be dropped from the start of the source sequence. + * This is a side-effect of the asynchrony introduced by the scheduler, where the action that causes callbacks from the source sequence to be forwarded + * may not execute immediately, despite the zero due time. + * + * Errors produced by the source sequence are always forwarded to the result sequence, even if the error occurs before the duration. + * @param {Number} duration Duration for skipping elements from the start of the sequence. + * @param {Scheduler} scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. + * @returns {Observable} An observable sequence with the elements skipped during the specified duration from the start of the source sequence. + */ + observableProto.skipWithTime = function (duration, scheduler) { + var source = this; + scheduler || (scheduler = timeoutScheduler); + return new AnonymousObservable(function (observer) { + var open = false, + t = scheduler.scheduleWithRelative(duration, function () { open = true; }), + d = source.subscribe(function (x) { + if (open) { + observer.onNext(x); + } + }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); + + return new CompositeDisposable(t, d); + }); + }; + + /** + * Skips elements from the observable source sequence until the specified start time, using the specified scheduler to run timers. + * Errors produced by the source sequence are always forwarded to the result sequence, even if the error occurs before the start time. + * + * @examples + * 1 - res = source.skipUntilWithTime(new Date(), [optional scheduler]); + * 2 - res = source.skipUntilWithTime(5000, [optional scheduler]); + * @param startTime Time to start taking elements from the source sequence. If this value is less than or equal to Date(), no elements will be skipped. + * @param scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. + * @returns {Observable} An observable sequence with the elements skipped until the specified start time. + */ + observableProto.skipUntilWithTime = function (startTime, scheduler) { + scheduler || (scheduler = timeoutScheduler); + var source = this, schedulerMethod = startTime instanceof Date ? + 'scheduleWithAbsolute' : + 'scheduleWithRelative'; + return new AnonymousObservable(function (observer) { + var open = false; + + return new CompositeDisposable( + scheduler[schedulerMethod](startTime, function () { open = true; }), + source.subscribe( + function (x) { open && observer.onNext(x); }, + observer.onError.bind(observer), + observer.onCompleted.bind(observer))); + }); + }; + + /** + * Takes elements for the specified duration until the specified end time, using the specified scheduler to run timers. + * + * @example + * 1 - res = source.takeUntilWithTime(new Date(), [optional scheduler]); + * 2 - res = source.takeUntilWithTime(5000, [optional scheduler]); + * @param {Number | Date} endTime Time to stop taking elements from the source sequence. If this value is less than or equal to new Date(), the result stream will complete immediately. + * @param {Scheduler} scheduler Scheduler to run the timer on. + * @returns {Observable} An observable sequence with the elements taken until the specified end time. + */ + observableProto.takeUntilWithTime = function (endTime, scheduler) { + scheduler || (scheduler = timeoutScheduler); + var source = this, schedulerMethod = endTime instanceof Date ? + 'scheduleWithAbsolute' : + 'scheduleWithRelative'; + return new AnonymousObservable(function (observer) { + return new CompositeDisposable(scheduler[schedulerMethod](endTime, function () { + observer.onCompleted(); + }), source.subscribe(observer)); + }); + }; + + var PausableObservable = (function (_super) { + + inherits(PausableObservable, _super); + + function subscribe(observer) { + var conn = this.source.publish(), + subscription = conn.subscribe(observer), + connection = disposableEmpty; + + var pausable = this.subject.distinctUntilChanged().subscribe(function (b) { + if (b) { + connection = conn.connect(); + } else { + connection.dispose(); + connection = disposableEmpty; + } + }); + + return new CompositeDisposable(subscription, connection, pausable); + } + + function PausableObservable(source, subject) { + this.source = source; + this.subject = subject || new Subject(); + this.isPaused = true; + _super.call(this, subscribe); + } + + PausableObservable.prototype.pause = function () { + if (this.isPaused === true){ + return; + } + this.isPaused = true; + this.subject.onNext(false); + }; + + PausableObservable.prototype.resume = function () { + if (this.isPaused === false){ + return; + } + this.isPaused = false; + this.subject.onNext(true); + }; + + return PausableObservable; + + }(Observable)); + + /** + * Pauses the underlying observable sequence based upon the observable sequence which yields true/false. + * @example + * var pauser = new Rx.Subject(); + * var source = Rx.Observable.interval(100).pausable(pauser); + * @param {Observable} pauser The observable sequence used to pause the underlying sequence. + * @returns {Observable} The observable sequence which is paused based upon the pauser. + */ + observableProto.pausable = function (pauser) { + return new PausableObservable(this, pauser); + }; + function combineLatestSource(source, subject, resultSelector) { + return new AnonymousObservable(function (observer) { + var n = 2, + hasValue = [false, false], + hasValueAll = false, + isDone = false, + values = new Array(n); + + function next(x, i) { + values[i] = x + var res; + hasValue[i] = true; + if (hasValueAll || (hasValueAll = hasValue.every(identity))) { + try { + res = resultSelector.apply(null, values); + } catch (ex) { + observer.onError(ex); + return; + } + observer.onNext(res); + } else if (isDone) { + observer.onCompleted(); + } + } + + return new CompositeDisposable( + source.subscribe( + function (x) { + next(x, 0); + }, + observer.onError.bind(observer), + function () { + isDone = true; + observer.onCompleted(); + }), + subject.subscribe( + function (x) { + next(x, 1); + }, + observer.onError.bind(observer)) + ); + }); + } + + var PausableBufferedObservable = (function (_super) { + + inherits(PausableBufferedObservable, _super); + + function subscribe(observer) { + var q = [], previous = true; + + var subscription = + combineLatestSource( + this.source, + this.subject.distinctUntilChanged(), + function (data, shouldFire) { + return { data: data, shouldFire: shouldFire }; + }) + .subscribe( + function (results) { + if (results.shouldFire && previous) { + observer.onNext(results.data); + } + if (results.shouldFire && !previous) { + while (q.length > 0) { + observer.onNext(q.shift()); + } + previous = true; + } else if (!results.shouldFire && !previous) { + q.push(results.data); + } else if (!results.shouldFire && previous) { + previous = false; + } + + }, + function (err) { + // Empty buffer before sending error + while (q.length > 0) { + observer.onNext(q.shift()); + } + observer.onError(err); + }, + function () { + // Empty buffer before sending completion + while (q.length > 0) { + observer.onNext(q.shift()); + } + observer.onCompleted(); + } + ); + + this.subject.onNext(false); + + return subscription; + } + + function PausableBufferedObservable(source, subject) { + this.source = source; + this.subject = subject || new Subject(); + this.isPaused = true; + _super.call(this, subscribe); + } + + PausableBufferedObservable.prototype.pause = function () { + if (this.isPaused === true){ + return; + } + this.isPaused = true; + this.subject.onNext(false); + }; + + PausableBufferedObservable.prototype.resume = function () { + if (this.isPaused === false){ + return; + } + this.isPaused = false; + this.subject.onNext(true); + }; + + return PausableBufferedObservable; + + }(Observable)); + + /** + * Pauses the underlying observable sequence based upon the observable sequence which yields true/false, + * and yields the values that were buffered while paused. + * @example + * var pauser = new Rx.Subject(); + * var source = Rx.Observable.interval(100).pausableBuffered(pauser); + * @param {Observable} pauser The observable sequence used to pause the underlying sequence. + * @returns {Observable} The observable sequence which is paused based upon the pauser. + */ + observableProto.pausableBuffered = function (subject) { + return new PausableBufferedObservable(this, subject); + }; + + /** + * Attaches a controller to the observable sequence with the ability to queue. + * @example + * var source = Rx.Observable.interval(100).controlled(); + * source.request(3); // Reads 3 values + * @param {Observable} pauser The observable sequence used to pause the underlying sequence. + * @returns {Observable} The observable sequence which is paused based upon the pauser. + */ + observableProto.controlled = function (enableQueue) { + if (enableQueue == null) { enableQueue = true; } + return new ControlledObservable(this, enableQueue); + }; + var ControlledObservable = (function (_super) { + + inherits(ControlledObservable, _super); + + function subscribe (observer) { + return this.source.subscribe(observer); + } + + function ControlledObservable (source, enableQueue) { + _super.call(this, subscribe); + this.subject = new ControlledSubject(enableQueue); + this.source = source.multicast(this.subject).refCount(); + } + + ControlledObservable.prototype.request = function (numberOfItems) { + if (numberOfItems == null) { numberOfItems = -1; } + return this.subject.request(numberOfItems); + }; + + return ControlledObservable; + + }(Observable)); + + var ControlledSubject = Rx.ControlledSubject = (function (_super) { + + function subscribe (observer) { + return this.subject.subscribe(observer); + } + + inherits(ControlledSubject, _super); + + function ControlledSubject(enableQueue) { + if (enableQueue == null) { + enableQueue = true; + } + + _super.call(this, subscribe); + this.subject = new Subject(); + this.enableQueue = enableQueue; + this.queue = enableQueue ? [] : null; + this.requestedCount = 0; + this.requestedDisposable = disposableEmpty; + this.error = null; + this.hasFailed = false; + this.hasCompleted = false; + this.controlledDisposable = disposableEmpty; + } + + addProperties(ControlledSubject.prototype, Observer, { + onCompleted: function () { + checkDisposed.call(this); + this.hasCompleted = true; + + if (!this.enableQueue || this.queue.length === 0) { + this.subject.onCompleted(); + } + }, + onError: function (error) { + checkDisposed.call(this); + this.hasFailed = true; + this.error = error; + + if (!this.enableQueue || this.queue.length === 0) { + this.subject.onError(error); + } + }, + onNext: function (value) { + checkDisposed.call(this); + var hasRequested = false; + + if (this.requestedCount === 0) { + if (this.enableQueue) { + this.queue.push(value); + } + } else { + if (this.requestedCount !== -1) { + if (this.requestedCount-- === 0) { + this.disposeCurrentRequest(); + } + } + hasRequested = true; + } + + if (hasRequested) { + this.subject.onNext(value); + } + }, + _processRequest: function (numberOfItems) { + if (this.enableQueue) { + //console.log('queue length', this.queue.length); + + while (this.queue.length >= numberOfItems && numberOfItems > 0) { + //console.log('number of items', numberOfItems); + this.subject.onNext(this.queue.shift()); + numberOfItems--; + } + + if (this.queue.length !== 0) { + return { numberOfItems: numberOfItems, returnValue: true }; + } else { + return { numberOfItems: numberOfItems, returnValue: false }; + } + } + + if (this.hasFailed) { + this.subject.onError(this.error); + this.controlledDisposable.dispose(); + this.controlledDisposable = disposableEmpty; + } else if (this.hasCompleted) { + this.subject.onCompleted(); + this.controlledDisposable.dispose(); + this.controlledDisposable = disposableEmpty; + } + + return { numberOfItems: numberOfItems, returnValue: false }; + }, + request: function (number) { + checkDisposed.call(this); + this.disposeCurrentRequest(); + var self = this, + r = this._processRequest(number); + + number = r.numberOfItems; + if (!r.returnValue) { + this.requestedCount = number; + this.requestedDisposable = disposableCreate(function () { + self.requestedCount = 0; + }); + + return this.requestedDisposable + } else { + return disposableEmpty; + } + }, + disposeCurrentRequest: function () { + this.requestedDisposable.dispose(); + this.requestedDisposable = disposableEmpty; + }, + + dispose: function () { + this.isDisposed = true; + this.error = null; + this.subject.dispose(); + this.requestedDisposable.dispose(); + } + }); + + return ControlledSubject; + }(Observable)); + /** + * Returns a new observable that triggers on the second and subsequent triggerings of the input observable. + * The Nth triggering of the input observable passes the arguments from the N-1th and Nth triggering as a pair. + * The argument passed to the N-1th triggering is held in hidden internal state until the Nth triggering occurs. + * @returns {Observable} An observable that triggers on successive pairs of observations from the input observable as an array. + */ + observableProto.pairwise = function () { + var source = this; + return new AnonymousObservable(function (observer) { + var previous, hasPrevious = false; + return source.subscribe( + function (x) { + if (hasPrevious) { + observer.onNext([previous, x]); + } else { + hasPrevious = true; + } + previous = x; + }, + observer.onError.bind(observer), + observer.onCompleted.bind(observer)); + }); + }; + /** + * Returns two observables which partition the observations of the source by the given function. + * The first will trigger observations for those values for which the predicate returns true. + * The second will trigger observations for those values where the predicate returns false. + * The predicate is executed once for each subscribed observer. + * Both also propagate all error observations arising from the source and each completes + * when the source completes. + * @param {Function} predicate + * The function to determine which output Observable will trigger a particular observation. + * @returns {Array} + * An array of observables. The first triggers when the predicate returns true, + * and the second triggers when the predicate returns false. + */ + observableProto.partition = function(predicate, thisArg) { + var published = this.publish().refCount(); + return [ + published.filter(predicate, thisArg), + published.filter(function (x, i, o) { return !predicate.call(thisArg, x, i, o); }) + ]; + }; + + /* + * Performs a exclusive waiting for the first to finish before subscribing to another observable. + * Observables that come in between subscriptions will be dropped on the floor. + * @returns {Observable} A exclusive observable with only the results that happen when subscribed. + */ + observableProto.exclusive = function () { + var sources = this; + return new AnonymousObservable(function (observer) { + var hasCurrent = false, + isStopped = false, + m = new SingleAssignmentDisposable(), + g = new CompositeDisposable(); + + g.add(m); + + m.setDisposable(sources.subscribe( + function (innerSource) { + if (!hasCurrent) { + hasCurrent = true; + + isPromise(innerSource) && (innerSource = observableFromPromise(innerSource)); + + var innerSubscription = new SingleAssignmentDisposable(); + g.add(innerSubscription); + + innerSubscription.setDisposable(innerSource.subscribe( + observer.onNext.bind(observer), + observer.onError.bind(observer), + function () { + g.remove(innerSubscription); + hasCurrent = false; + if (isStopped && g.length === 1) { + observer.onCompleted(); + } + })); + } + }, + observer.onError.bind(observer), + function () { + isStopped = true; + if (!hasCurrent && g.length === 1) { + observer.onCompleted(); + } + })); + + return g; + }); + }; + /* + * Performs a exclusive map waiting for the first to finish before subscribing to another observable. + * Observables that come in between subscriptions will be dropped on the floor. + * @param {Function} selector Selector to invoke for every item in the current subscription. + * @param {Any} [thisArg] An optional context to invoke with the selector parameter. + * @returns {Observable} An exclusive observable with only the results that happen when subscribed. + */ + observableProto.exclusiveMap = function (selector, thisArg) { + var sources = this; + return new AnonymousObservable(function (observer) { + var index = 0, + hasCurrent = false, + isStopped = true, + m = new SingleAssignmentDisposable(), + g = new CompositeDisposable(); + + g.add(m); + + m.setDisposable(sources.subscribe( + function (innerSource) { + + if (!hasCurrent) { + hasCurrent = true; + + innerSubscription = new SingleAssignmentDisposable(); + g.add(innerSubscription); + + isPromise(innerSource) && (innerSource = observableFromPromise(innerSource)); + + innerSubscription.setDisposable(innerSource.subscribe( + function (x) { + var result; + try { + result = selector.call(thisArg, x, index++, innerSource); + } catch (e) { + observer.onError(e); + return; + } + + observer.onNext(result); + }, + observer.onError.bind(observer), + function () { + g.remove(innerSubscription); + hasCurrent = false; + + if (isStopped && g.length === 1) { + observer.onCompleted(); + } + })); + } + }, + observer.onError.bind(observer), + function () { + isStopped = true; + if (g.length === 1 && !hasCurrent) { + observer.onCompleted(); + } + })); + return g; + }); + }; + var AnonymousObservable = Rx.AnonymousObservable = (function (__super__) { + inherits(AnonymousObservable, __super__); + + // Fix subscriber to check for undefined or function returned to decorate as Disposable + function fixSubscriber(subscriber) { + if (typeof subscriber === 'undefined') { + subscriber = disposableEmpty; + } else if (typeof subscriber === 'function') { + subscriber = disposableCreate(subscriber); + } + + return subscriber; + } + + function AnonymousObservable(subscribe) { + if (!(this instanceof AnonymousObservable)) { + return new AnonymousObservable(subscribe); + } + + function s(observer) { + var setDisposable = function () { + try { + autoDetachObserver.setDisposable(fixSubscriber(subscribe(autoDetachObserver))); + } catch (e) { + if (!autoDetachObserver.fail(e)) { + throw e; + } + } + }; + + var autoDetachObserver = new AutoDetachObserver(observer); + if (currentThreadScheduler.scheduleRequired()) { + currentThreadScheduler.schedule(setDisposable); + } else { + setDisposable(); + } + + return autoDetachObserver; + } + + __super__.call(this, s); + } + + return AnonymousObservable; + + }(Observable)); + + /** @private */ + var AutoDetachObserver = (function (_super) { + inherits(AutoDetachObserver, _super); + + function AutoDetachObserver(observer) { + _super.call(this); + this.observer = observer; + this.m = new SingleAssignmentDisposable(); + } + + var AutoDetachObserverPrototype = AutoDetachObserver.prototype; + + AutoDetachObserverPrototype.next = function (value) { + var noError = false; + try { + this.observer.onNext(value); + noError = true; + } catch (e) { + throw e; + } finally { + if (!noError) { + this.dispose(); + } + } + }; + + AutoDetachObserverPrototype.error = function (exn) { + try { + this.observer.onError(exn); + } catch (e) { + throw e; + } finally { + this.dispose(); + } + }; + + AutoDetachObserverPrototype.completed = function () { + try { + this.observer.onCompleted(); + } catch (e) { + throw e; + } finally { + this.dispose(); + } + }; + + AutoDetachObserverPrototype.setDisposable = function (value) { this.m.setDisposable(value); }; + AutoDetachObserverPrototype.getDisposable = function (value) { return this.m.getDisposable(); }; + /* @private */ + AutoDetachObserverPrototype.disposable = function (value) { + return arguments.length ? this.getDisposable() : setDisposable(value); + }; + + AutoDetachObserverPrototype.dispose = function () { + _super.prototype.dispose.call(this); + this.m.dispose(); + }; + + return AutoDetachObserver; + }(AbstractObserver)); + + /** @private */ + var InnerSubscription = function (subject, observer) { + this.subject = subject; + this.observer = observer; + }; + + /** + * @private + * @memberOf InnerSubscription + */ + InnerSubscription.prototype.dispose = function () { + if (!this.subject.isDisposed && this.observer !== null) { + var idx = this.subject.observers.indexOf(this.observer); + this.subject.observers.splice(idx, 1); + this.observer = null; + } + }; + + /** + * Represents an object that is both an observable sequence as well as an observer. + * Each notification is broadcasted to all subscribed observers. + */ + var Subject = Rx.Subject = (function (_super) { + function subscribe(observer) { + checkDisposed.call(this); + if (!this.isStopped) { + this.observers.push(observer); + return new InnerSubscription(this, observer); + } + if (this.exception) { + observer.onError(this.exception); + return disposableEmpty; + } + observer.onCompleted(); + return disposableEmpty; + } + + inherits(Subject, _super); + + /** + * Creates a subject. + * @constructor + */ + function Subject() { + _super.call(this, subscribe); + this.isDisposed = false, + this.isStopped = false, + this.observers = []; + } + + addProperties(Subject.prototype, Observer, { + /** + * Indicates whether the subject has observers subscribed to it. + * @returns {Boolean} Indicates whether the subject has observers subscribed to it. + */ + hasObservers: function () { + return this.observers.length > 0; + }, + /** + * Notifies all subscribed observers about the end of the sequence. + */ + onCompleted: function () { + checkDisposed.call(this); + if (!this.isStopped) { + var os = this.observers.slice(0); + this.isStopped = true; + for (var i = 0, len = os.length; i < len; i++) { + os[i].onCompleted(); + } + + this.observers = []; + } + }, + /** + * Notifies all subscribed observers about the exception. + * @param {Mixed} error The exception to send to all observers. + */ + onError: function (exception) { + checkDisposed.call(this); + if (!this.isStopped) { + var os = this.observers.slice(0); + this.isStopped = true; + this.exception = exception; + for (var i = 0, len = os.length; i < len; i++) { + os[i].onError(exception); + } + + this.observers = []; + } + }, + /** + * Notifies all subscribed observers about the arrival of the specified element in the sequence. + * @param {Mixed} value The value to send to all observers. + */ + onNext: function (value) { + checkDisposed.call(this); + if (!this.isStopped) { + var os = this.observers.slice(0); + for (var i = 0, len = os.length; i < len; i++) { + os[i].onNext(value); + } + } + }, + /** + * Unsubscribe all observers and release resources. + */ + dispose: function () { + this.isDisposed = true; + this.observers = null; + } + }); + + /** + * Creates a subject from the specified observer and observable. + * @param {Observer} observer The observer used to send messages to the subject. + * @param {Observable} observable The observable used to subscribe to messages sent from the subject. + * @returns {Subject} Subject implemented using the given observer and observable. + */ + Subject.create = function (observer, observable) { + return new AnonymousSubject(observer, observable); + }; + + return Subject; + }(Observable)); + + /** + * Represents the result of an asynchronous operation. + * The last value before the OnCompleted notification, or the error received through OnError, is sent to all subscribed observers. + */ + var AsyncSubject = Rx.AsyncSubject = (function (_super) { + + function subscribe(observer) { + checkDisposed.call(this); + + if (!this.isStopped) { + this.observers.push(observer); + return new InnerSubscription(this, observer); + } + + var ex = this.exception, + hv = this.hasValue, + v = this.value; + + if (ex) { + observer.onError(ex); + } else if (hv) { + observer.onNext(v); + observer.onCompleted(); + } else { + observer.onCompleted(); + } + + return disposableEmpty; + } + + inherits(AsyncSubject, _super); + + /** + * Creates a subject that can only receive one value and that value is cached for all future observations. + * @constructor + */ + function AsyncSubject() { + _super.call(this, subscribe); + + this.isDisposed = false; + this.isStopped = false; + this.value = null; + this.hasValue = false; + this.observers = []; + this.exception = null; + } + + addProperties(AsyncSubject.prototype, Observer, { + /** + * Indicates whether the subject has observers subscribed to it. + * @returns {Boolean} Indicates whether the subject has observers subscribed to it. + */ + hasObservers: function () { + checkDisposed.call(this); + return this.observers.length > 0; + }, + /** + * Notifies all subscribed observers about the end of the sequence, also causing the last received value to be sent out (if any). + */ + onCompleted: function () { + var o, i, len; + checkDisposed.call(this); + if (!this.isStopped) { + this.isStopped = true; + var os = this.observers.slice(0), + v = this.value, + hv = this.hasValue; + + if (hv) { + for (i = 0, len = os.length; i < len; i++) { + o = os[i]; + o.onNext(v); + o.onCompleted(); + } + } else { + for (i = 0, len = os.length; i < len; i++) { + os[i].onCompleted(); + } + } + + this.observers = []; + } + }, + /** + * Notifies all subscribed observers about the exception. + * @param {Mixed} error The exception to send to all observers. + */ + onError: function (exception) { + checkDisposed.call(this); + if (!this.isStopped) { + var os = this.observers.slice(0); + this.isStopped = true; + this.exception = exception; + + for (var i = 0, len = os.length; i < len; i++) { + os[i].onError(exception); + } + + this.observers = []; + } + }, + /** + * Sends a value to the subject. The last value received before successful termination will be sent to all subscribed and future observers. + * @param {Mixed} value The value to store in the subject. + */ + onNext: function (value) { + checkDisposed.call(this); + if (!this.isStopped) { + this.value = value; + this.hasValue = true; + } + }, + /** + * Unsubscribe all observers and release resources. + */ + dispose: function () { + this.isDisposed = true; + this.observers = null; + this.exception = null; + this.value = null; + } + }); + + return AsyncSubject; + }(Observable)); + + /** @private */ + var AnonymousSubject = (function (_super) { + inherits(AnonymousSubject, _super); + + function subscribe(observer) { + return this.observable.subscribe(observer); + } + + /** + * @private + * @constructor + */ + function AnonymousSubject(observer, observable) { + _super.call(this, subscribe); + this.observer = observer; + this.observable = observable; + } + + addProperties(AnonymousSubject.prototype, Observer, { + /** + * @private + * @memberOf AnonymousSubject# + */ + onCompleted: function () { + this.observer.onCompleted(); + }, + /** + * @private + * @memberOf AnonymousSubject# + */ + onError: function (exception) { + this.observer.onError(exception); + }, + /** + * @private + * @memberOf AnonymousSubject# + */ + onNext: function (value) { + this.observer.onNext(value); + } + }); + + return AnonymousSubject; + }(Observable)); + + /** + * Represents a value that changes over time. + * Observers can subscribe to the subject to receive the last (or initial) value and all subsequent notifications. + */ + var BehaviorSubject = Rx.BehaviorSubject = (function (_super) { + function subscribe(observer) { + checkDisposed.call(this); + if (!this.isStopped) { + this.observers.push(observer); + observer.onNext(this.value); + return new InnerSubscription(this, observer); + } + var ex = this.exception; + if (ex) { + observer.onError(ex); + } else { + observer.onCompleted(); + } + return disposableEmpty; + } + + inherits(BehaviorSubject, _super); + + /** + * @constructor + * Initializes a new instance of the BehaviorSubject class which creates a subject that caches its last value and starts with the specified value. + * @param {Mixed} value Initial value sent to observers when no other value has been received by the subject yet. + */ + function BehaviorSubject(value) { + _super.call(this, subscribe); + + this.value = value, + this.observers = [], + this.isDisposed = false, + this.isStopped = false, + this.exception = null; + } + + addProperties(BehaviorSubject.prototype, Observer, { + /** + * Indicates whether the subject has observers subscribed to it. + * @returns {Boolean} Indicates whether the subject has observers subscribed to it. + */ + hasObservers: function () { + return this.observers.length > 0; + }, + /** + * Notifies all subscribed observers about the end of the sequence. + */ + onCompleted: function () { + checkDisposed.call(this); + if (!this.isStopped) { + var os = this.observers.slice(0); + this.isStopped = true; + for (var i = 0, len = os.length; i < len; i++) { + os[i].onCompleted(); + } + + this.observers = []; + } + }, + /** + * Notifies all subscribed observers about the exception. + * @param {Mixed} error The exception to send to all observers. + */ + onError: function (error) { + checkDisposed.call(this); + if (!this.isStopped) { + var os = this.observers.slice(0); + this.isStopped = true; + this.exception = error; + + for (var i = 0, len = os.length; i < len; i++) { + os[i].onError(error); + } + + this.observers = []; + } + }, + /** + * Notifies all subscribed observers about the arrival of the specified element in the sequence. + * @param {Mixed} value The value to send to all observers. + */ + onNext: function (value) { + checkDisposed.call(this); + if (!this.isStopped) { + this.value = value; + var os = this.observers.slice(0); + for (var i = 0, len = os.length; i < len; i++) { + os[i].onNext(value); + } + } + }, + /** + * Unsubscribe all observers and release resources. + */ + dispose: function () { + this.isDisposed = true; + this.observers = null; + this.value = null; + this.exception = null; + } + }); + + return BehaviorSubject; + }(Observable)); + + /** + * Represents an object that is both an observable sequence as well as an observer. + * Each notification is broadcasted to all subscribed and future observers, subject to buffer trimming policies. + */ + var ReplaySubject = Rx.ReplaySubject = (function (_super) { + + function RemovableDisposable (subject, observer) { + this.subject = subject; + this.observer = observer; + }; + + RemovableDisposable.prototype.dispose = function () { + this.observer.dispose(); + if (!this.subject.isDisposed) { + var idx = this.subject.observers.indexOf(this.observer); + this.subject.observers.splice(idx, 1); + } + }; + + function subscribe(observer) { + var so = new ScheduledObserver(this.scheduler, observer), + subscription = new RemovableDisposable(this, so); + checkDisposed.call(this); + this._trim(this.scheduler.now()); + this.observers.push(so); + + var n = this.q.length; + + for (var i = 0, len = this.q.length; i < len; i++) { + so.onNext(this.q[i].value); + } + + if (this.hasError) { + n++; + so.onError(this.error); + } else if (this.isStopped) { + n++; + so.onCompleted(); + } + + so.ensureActive(n); + return subscription; + } + + inherits(ReplaySubject, _super); + + /** + * Initializes a new instance of the ReplaySubject class with the specified buffer size, window size and scheduler. + * @param {Number} [bufferSize] Maximum element count of the replay buffer. + * @param {Number} [windowSize] Maximum time length of the replay buffer. + * @param {Scheduler} [scheduler] Scheduler the observers are invoked on. + */ + function ReplaySubject(bufferSize, windowSize, scheduler) { + this.bufferSize = bufferSize == null ? Number.MAX_VALUE : bufferSize; + this.windowSize = windowSize == null ? Number.MAX_VALUE : windowSize; + this.scheduler = scheduler || currentThreadScheduler; + this.q = []; + this.observers = []; + this.isStopped = false; + this.isDisposed = false; + this.hasError = false; + this.error = null; + _super.call(this, subscribe); + } + + addProperties(ReplaySubject.prototype, Observer, { + /** + * Indicates whether the subject has observers subscribed to it. + * @returns {Boolean} Indicates whether the subject has observers subscribed to it. + */ + hasObservers: function () { + return this.observers.length > 0; + }, + /* @private */ + _trim: function (now) { + while (this.q.length > this.bufferSize) { + this.q.shift(); + } + while (this.q.length > 0 && (now - this.q[0].interval) > this.windowSize) { + this.q.shift(); + } + }, + /** + * Notifies all subscribed observers about the arrival of the specified element in the sequence. + * @param {Mixed} value The value to send to all observers. + */ + onNext: function (value) { + var observer; + checkDisposed.call(this); + if (!this.isStopped) { + var now = this.scheduler.now(); + this.q.push({ interval: now, value: value }); + this._trim(now); + + var o = this.observers.slice(0); + for (var i = 0, len = o.length; i < len; i++) { + observer = o[i]; + observer.onNext(value); + observer.ensureActive(); + } + } + }, + /** + * Notifies all subscribed observers about the exception. + * @param {Mixed} error The exception to send to all observers. + */ + onError: function (error) { + var observer; + checkDisposed.call(this); + if (!this.isStopped) { + this.isStopped = true; + this.error = error; + this.hasError = true; + var now = this.scheduler.now(); + this._trim(now); + var o = this.observers.slice(0); + for (var i = 0, len = o.length; i < len; i++) { + observer = o[i]; + observer.onError(error); + observer.ensureActive(); + } + this.observers = []; + } + }, + /** + * Notifies all subscribed observers about the end of the sequence. + */ + onCompleted: function () { + var observer; + checkDisposed.call(this); + if (!this.isStopped) { + this.isStopped = true; + var now = this.scheduler.now(); + this._trim(now); + var o = this.observers.slice(0); + for (var i = 0, len = o.length; i < len; i++) { + observer = o[i]; + observer.onCompleted(); + observer.ensureActive(); + } + this.observers = []; + } + }, + /** + * Unsubscribe all observers and release resources. + */ + dispose: function () { + this.isDisposed = true; + this.observers = null; + } + }); + + return ReplaySubject; + }(Observable)); + + if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) { + root.Rx = Rx; + + define(function() { + return Rx; + }); + } else if (freeExports && freeModule) { + // in Node.js or RingoJS + if (moduleExports) { + (freeModule.exports = Rx).Rx = Rx; + } else { + freeExports.Rx = Rx; + } + } else { + // in a browser or Rhino + root.Rx = Rx; + } +}.call(this)); \ No newline at end of file diff --git a/ajax/libs/rxjs/2.2.28/rx.lite.min.js b/ajax/libs/rxjs/2.2.28/rx.lite.min.js new file mode 100644 index 000000000..34df4472a --- /dev/null +++ b/ajax/libs/rxjs/2.2.28/rx.lite.min.js @@ -0,0 +1,2 @@ +(function(t){function e(){if(this.isDisposed)throw Error(V)}function n(t){var e=typeof t;return t&&("function"==e||"object"==e)||!1}function r(t){var e=[];if(!n(t))return e;ue.nonEnumArgs&&t.length&&u(t)&&(t=ae.call(t));var r=ue.enumPrototypes&&"function"==typeof t,i=ue.enumErrorProps&&(t===ee||t instanceof Error);for(var o in t)r&&"prototype"==o||i&&("message"==o||"name"==o)||e.push(o);if(ue.nonEnumShadows&&t!==ne){var s=t.constructor,c=-1,a=oe.length;if(t===(s&&s.prototype))var h=t===stringProto?X:t===ee?Q:G.call(t),l=se[h];for(;a>++c;)o=oe[c],l&&l[o]||!Y.call(t,o)||e.push(o)}return e}function i(t,e,n){for(var r=-1,i=n(t),o=i.length;o>++r;){var s=i[r];if(e(t[s],s,t)===!1)break}return t}function o(t,e){return i(t,e,r)}function s(t){return"function"!=typeof t.toString&&"string"==typeof(t+"")}function u(t){return t&&"object"==typeof t?G.call(t)==F:!1}function c(t){return"function"==typeof t||!1}function a(e,n,r,i){if(e===n)return 0!==e||1/e==1/n;var h=typeof e,l=typeof n;if(e===e&&(null==e||null==n||"function"!=h&&"object"!=h&&"function"!=l&&"object"!=l))return!1;var f=G.call(e),p=G.call(n);if(f==F&&(f=J),p==F&&(p=J),f!=p)return!1;switch(f){case U:case H:return+e==+n;case K:return e!=+e?n!=+n:0==e?1/e==1/n:e==+n;case Z:case X:return e==n+""}var d=f==B;if(!d){if(f!=J||!ue.nodeClass&&(s(e)||s(n)))return!1;var b=!ue.argsObject&&u(e)?Object:e.constructor,v=!ue.argsObject&&u(n)?Object:n.constructor;if(!(b==v||Y.call(e,"constructor")&&Y.call(n,"constructor")||c(b)&&b instanceof b&&c(v)&&v instanceof v||!("constructor"in e&&"constructor"in n)))return!1}r||(r=[]),i||(i=[]);for(var m=r.length;m--;)if(r[m]==e)return i[m]==n;var y=0;if(result=!0,r.push(e),i.push(n),d){if(m=e.length,y=n.length,result=y==m)for(;y--;){var w=n[y];if(!(result=a(e[y],w,r,i)))break}}else o(n,function(n,o,s){return Y.call(s,o)?(y++,result=Y.call(e,o)&&a(e[o],n,r,i)):t}),result&&o(e,function(e,n,r){return Y.call(r,n)?result=--y>-1:t});return r.pop(),i.pop(),result}function h(t,e){return 1===t.length&&Array.isArray(t[e])?t[e]:ae.call(t)}function l(t,e){for(var n=Array(t),r=0;t>r;r++)n[r]=e();return n}function f(e,n){return new dn(function(r){var i=new Ee,o=new xe;return o.setDisposable(i),i.setDisposable(e.subscribe(r.onNext.bind(r),function(e){var i,s;try{s=n(e)}catch(u){return r.onError(u),t}T(s)&&(s=sn(s)),i=new Ee,o.setDisposable(i),i.setDisposable(s.subscribe(r))},r.onCompleted.bind(r))),o})}function p(e,n){var r=this;return new dn(function(i){var o=0,s=e.length;return r.subscribe(function(r){if(s>o){var u,c=e[o++];try{u=n(r,c)}catch(a){return i.onError(a),t}i.onNext(u)}else i.onCompleted()},i.onError.bind(i),i.onCompleted.bind(i))})}function d(t){return this.map(function(e,n){var r=t(e,n);return T(r)?sn(r):r}).concatAll()}function b(t){return this.select(function(e,n){var r=t(e,n);return T(r)?sn(r):r}).mergeObservable()}function v(t,e,n){if(t.addListener)return t.addListener(e,n),ye(function(){t.removeListener(e,n)});if(t.addEventListener)return t.addEventListener(e,n,!1),ye(function(){t.removeEventListener(e,n,!1)});throw Error("No listener found")}function m(t,e,n){var r=new be;if("function"==typeof t.item&&"number"==typeof t.length)for(var i=0,o=t.length;o>i;i++)r.add(m(t.item(i),e,n));else t&&r.add(v(t,e,n));return r}function y(t,e){var n=Se(t);return new dn(function(t){return e.scheduleWithRelative(n,function(){t.onNext(0),t.onCompleted()})})}function w(t,e,n){return t===e?new dn(function(t){return n.schedulePeriodicWithState(0,e,function(e){return t.onNext(e),e+1})}):Qe(function(){return g(n.now()+t,e,n)})}function g(t,e,n){var r=Se(e);return new dn(function(e){var i=0,o=t;return n.scheduleRecursiveWithAbsolute(o,function(t){var s;r>0&&(s=n.now(),o+=r,s>=o&&(o=s+r)),e.onNext(i++),t(o)})})}function E(t,e){return new dn(function(n){function r(){s&&(s=!1,n.onNext(o)),i&&n.onCompleted()}var i,o,s;return new be(t.subscribe(function(t){s=!0,o=t},n.onError.bind(n),function(){i=!0}),e.subscribe(r,n.onError.bind(n),r))})}function x(e,n,r){return new dn(function(i){function o(e,n){h[n]=e;var o;if(u[n]=!0,c||(c=u.every(j))){try{o=r.apply(null,h)}catch(s){return i.onError(s),t}i.onNext(o)}else a&&i.onCompleted()}var s=2,u=[!1,!1],c=!1,a=!1,h=Array(s);return new be(e.subscribe(function(t){o(t,0)},i.onError.bind(i),function(){a=!0,i.onCompleted()}),n.subscribe(function(t){o(t,1)},i.onError.bind(i)))})}var C={"boolean":!1,"function":!0,object:!0,number:!1,string:!1,undefined:!1},D=C[typeof window]&&window||this,S=C[typeof exports]&&exports&&!exports.nodeType&&exports,N=C[typeof module]&&module&&!module.nodeType&&module,A=N&&N.exports===S&&S,_=C[typeof global]&&global;!_||_.global!==_&&_.window!==_||(D=_);var O={internals:{},config:{Promise:D.Promise},helpers:{}},R=O.helpers.noop=function(){},j=O.helpers.identity=function(t){return t},W=(O.helpers.pluck=function(t){return function(e){return e[t]}},O.helpers.just=function(t){return function(){return t}},O.helpers.defaultNow=Date.now),k=O.helpers.defaultComparer=function(t,e){return ce(t,e)},q=O.helpers.defaultSubComparer=function(t,e){return t>e?1:e>t?-1:0},P=(O.helpers.defaultKeySerializer=function(t){return""+t},O.helpers.defaultError=function(t){throw t}),T=O.helpers.isPromise=function(t){return!!t&&"function"==typeof t.then&&t.then!==O.Observable.prototype.then};O.helpers.asArray=function(){return Array.prototype.slice.call(arguments)},O.helpers.not=function(t){return!t};var L="Argument out of range",V="Object has been disposed",z="object"==typeof Symbol&&Symbol.iterator||"_es6shim_iterator_";D.Set&&"function"==typeof(new D.Set)["@@iterator"]&&(z="@@iterator");var M,I={done:!0,value:t},F="[object Arguments]",B="[object Array]",U="[object Boolean]",H="[object Date]",Q="[object Error]",$="[object Function]",K="[object Number]",J="[object Object]",Z="[object RegExp]",X="[object String]",G=Object.prototype.toString,Y=Object.prototype.hasOwnProperty,te=G.call(arguments)==F,ee=Error.prototype,ne=Object.prototype,re=ne.propertyIsEnumerable;try{M=!(G.call(document)==J&&!({toString:0}+""))}catch(ie){M=!0}var oe=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],se={};se[B]=se[H]=se[K]={constructor:!0,toLocaleString:!0,toString:!0,valueOf:!0},se[U]=se[X]={constructor:!0,toString:!0,valueOf:!0},se[Q]=se[$]=se[Z]={constructor:!0,toString:!0},se[J]={constructor:!0};var ue={};(function(){var t=function(){this.x=1},e=[];t.prototype={valueOf:1,y:1};for(var n in new t)e.push(n);for(n in arguments);ue.enumErrorProps=re.call(ee,"message")||re.call(ee,"name"),ue.enumPrototypes=re.call(t,"prototype"),ue.nonEnumArgs=0!=n,ue.nonEnumShadows=!/valueOf/.test(e)})(1),te||(u=function(t){return t&&"object"==typeof t?Y.call(t,"callee"):!1}),c(/x/)&&(c=function(t){return"function"==typeof t&&G.call(t)==$});var ce=O.internals.isEqual=function(t,e){return a(t,e,[],[])},ae=Array.prototype.slice;({}).hasOwnProperty;var he=this.inherits=O.internals.inherits=function(t,e){function n(){this.constructor=t}n.prototype=e.prototype,t.prototype=new n},le=O.internals.addProperties=function(t){for(var e=ae.call(arguments,1),n=0,r=e.length;r>n;n++){var i=e[n];for(var o in i)t[o]=i[o]}};O.internals.addRef=function(t,e){return new dn(function(n){return new be(e.getDisposable(),t.subscribe(n))})};var fe=function(t,e){this.id=t,this.value=e};fe.prototype.compareTo=function(t){var e=this.value.compareTo(t.value);return 0===e&&(e=this.id-t.id),e};var pe=O.internals.PriorityQueue=function(t){this.items=Array(t),this.length=0},de=pe.prototype;de.isHigherPriority=function(t,e){return 0>this.items[t].compareTo(this.items[e])},de.percolate=function(t){if(!(t>=this.length||0>t)){var e=t-1>>1;if(!(0>e||e===t)&&this.isHigherPriority(t,e)){var n=this.items[t];this.items[t]=this.items[e],this.items[e]=n,this.percolate(e)}}},de.heapify=function(e){if(e===t&&(e=0),!(e>=this.length||0>e)){var n=2*e+1,r=2*e+2,i=e;if(this.length>n&&this.isHigherPriority(n,i)&&(i=n),this.length>r&&this.isHigherPriority(r,i)&&(i=r),i!==e){var o=this.items[e];this.items[e]=this.items[i],this.items[i]=o,this.heapify(i)}}},de.peek=function(){return this.items[0].value},de.removeAt=function(t){this.items[t]=this.items[--this.length],delete this.items[this.length],this.heapify()},de.dequeue=function(){var t=this.peek();return this.removeAt(0),t},de.enqueue=function(t){var e=this.length++;this.items[e]=new fe(pe.count++,t),this.percolate(e)},de.remove=function(t){for(var e=0;this.length>e;e++)if(this.items[e].value===t)return this.removeAt(e),!0;return!1},pe.count=0;var be=O.CompositeDisposable=function(){this.disposables=h(arguments,0),this.isDisposed=!1,this.length=this.disposables.length},ve=be.prototype;ve.add=function(t){this.isDisposed?t.dispose():(this.disposables.push(t),this.length++)},ve.remove=function(t){var e=!1;if(!this.isDisposed){var n=this.disposables.indexOf(t);-1!==n&&(e=!0,this.disposables.splice(n,1),this.length--,t.dispose())}return e},ve.dispose=function(){if(!this.isDisposed){this.isDisposed=!0;var t=this.disposables.slice(0);this.disposables=[],this.length=0;for(var e=0,n=t.length;n>e;e++)t[e].dispose()}},ve.clear=function(){var t=this.disposables.slice(0);this.disposables=[],this.length=0;for(var e=0,n=t.length;n>e;e++)t[e].dispose()},ve.contains=function(t){return-1!==this.disposables.indexOf(t)},ve.toArray=function(){return this.disposables.slice(0)};var me=O.Disposable=function(t){this.isDisposed=!1,this.action=t||R};me.prototype.dispose=function(){this.isDisposed||(this.action(),this.isDisposed=!0)};var ye=me.create=function(t){return new me(t)},we=me.empty={dispose:R},ge=function(){function t(t){this.isSingle=t,this.isDisposed=!1,this.current=null}var e=t.prototype;return e.getDisposable=function(){return this.current},e.setDisposable=function(t){if(this.current&&this.isSingle)throw Error("Disposable has already been assigned");var e,n=this.isDisposed;n||(e=this.current,this.current=t),e&&e.dispose(),n&&t&&t.dispose()},e.dispose=function(){var t;this.isDisposed||(this.isDisposed=!0,t=this.current,this.current=null),t&&t.dispose()},t}(),Ee=O.SingleAssignmentDisposable=function(t){function e(){t.call(this,!0)}return he(e,t),e}(ge),xe=O.SerialDisposable=function(t){function e(){t.call(this,!1)}return he(e,t),e}(ge);O.RefCountDisposable=function(){function t(t){this.disposable=t,this.disposable.count++,this.isInnerDisposed=!1}function e(t){this.underlyingDisposable=t,this.isDisposed=!1,this.isPrimaryDisposed=!1,this.count=0}return t.prototype.dispose=function(){this.disposable.isDisposed||this.isInnerDisposed||(this.isInnerDisposed=!0,this.disposable.count--,0===this.disposable.count&&this.disposable.isPrimaryDisposed&&(this.disposable.isDisposed=!0,this.disposable.underlyingDisposable.dispose()))},e.prototype.dispose=function(){this.isDisposed||this.isPrimaryDisposed||(this.isPrimaryDisposed=!0,0===this.count&&(this.isDisposed=!0,this.underlyingDisposable.dispose()))},e.prototype.getDisposable=function(){return this.isDisposed?we:new t(this)},e}();var Ce=O.internals.ScheduledItem=function(t,e,n,r,i){this.scheduler=t,this.state=e,this.action=n,this.dueTime=r,this.comparer=i||q,this.disposable=new Ee};Ce.prototype.invoke=function(){this.disposable.setDisposable(this.invokeCore())},Ce.prototype.compareTo=function(t){return this.comparer(this.dueTime,t.dueTime)},Ce.prototype.isCancelled=function(){return this.disposable.isDisposed},Ce.prototype.invokeCore=function(){return this.action(this.scheduler,this.state)};var De=O.Scheduler=function(){function t(t,e,n,r){this.now=t,this._schedule=e,this._scheduleRelative=n,this._scheduleAbsolute=r}function e(t,e){var n=e.first,r=e.second,i=new be,o=function(e){r(e,function(e){var n=!1,r=!1,s=t.scheduleWithState(e,function(t,e){return n?i.remove(s):r=!0,o(e),we});r||(i.add(s),n=!0)})};return o(n),i}function n(t,e,n){var r=e.first,i=e.second,o=new be,s=function(e){i(e,function(e,r){var i=!1,u=!1,c=t[n].call(t,e,r,function(t,e){return i?o.remove(c):u=!0,s(e),we});u||(o.add(c),i=!0)})};return s(r),o}function r(t,e){return e(),we}var i=t.prototype;return i.schedulePeriodic=function(t,e){return this.schedulePeriodicWithState(null,t,function(){e()})},i.schedulePeriodicWithState=function(t,e,n){var r=t,i=setInterval(function(){r=n(r)},e);return ye(function(){clearInterval(i)})},i.schedule=function(t){return this._schedule(t,r)},i.scheduleWithState=function(t,e){return this._schedule(t,e)},i.scheduleWithRelative=function(t,e){return this._scheduleRelative(e,t,r)},i.scheduleWithRelativeAndState=function(t,e,n){return this._scheduleRelative(t,e,n)},i.scheduleWithAbsolute=function(t,e){return this._scheduleAbsolute(e,t,r)},i.scheduleWithAbsoluteAndState=function(t,e,n){return this._scheduleAbsolute(t,e,n)},i.scheduleRecursive=function(t){return this.scheduleRecursiveWithState(t,function(t,e){t(function(){e(t)})})},i.scheduleRecursiveWithState=function(t,n){return this.scheduleWithState({first:t,second:n},function(t,n){return e(t,n)})},i.scheduleRecursiveWithRelative=function(t,e){return this.scheduleRecursiveWithRelativeAndState(e,t,function(t,e){t(function(n){e(t,n)})})},i.scheduleRecursiveWithRelativeAndState=function(t,e,r){return this._scheduleRelative({first:t,second:r},e,function(t,e){return n(t,e,"scheduleWithRelativeAndState")})},i.scheduleRecursiveWithAbsolute=function(t,e){return this.scheduleRecursiveWithAbsoluteAndState(e,t,function(t,e){t(function(n){e(t,n)})})},i.scheduleRecursiveWithAbsoluteAndState=function(t,e,r){return this._scheduleAbsolute({first:t,second:r},e,function(t,e){return n(t,e,"scheduleWithAbsoluteAndState")})},t.now=W,t.normalize=function(t){return 0>t&&(t=0),t},t}(),Se=De.normalize,Ne=De.immediate=function(){function t(t,e){return e(this,t)}function e(t,e,n){for(var r=Se(r);r-this.now()>0;);return n(this,t)}function n(t,e,n){return this.scheduleWithRelativeAndState(t,e-this.now(),n)}return new De(W,t,e,n)}(),Ae=De.currentThread=function(){function t(t){for(var e;t.length>0;)if(e=t.dequeue(),!e.isCancelled()){for(;e.dueTime-De.now()>0;);e.isCancelled()||e.invoke()}}function e(t,e){return this.scheduleWithRelativeAndState(t,0,e)}function n(e,n,r){var o=this.now()+De.normalize(n),s=new Ce(this,e,r,o);if(i)i.enqueue(s);else{i=new pe(4),i.enqueue(s);try{t(i)}catch(u){throw u}finally{i=null}}return s.disposable}function r(t,e,n){return this.scheduleWithRelativeAndState(t,e-this.now(),n)}var i,o=new De(W,e,n,r);return o.scheduleRequired=function(){return null===i},o.ensureTrampoline=function(t){return null===i?this.schedule(t):t()},o}();O.internals.SchedulePeriodicRecursive=function(){function t(t,e){e(0,this._period);try{this._state=this._action(this._state)}catch(n){throw this._cancel.dispose(),n}}function e(t,e,n,r){this._scheduler=t,this._state=e,this._period=n,this._action=r}return e.prototype.start=function(){var e=new Ee;return this._cancel=e,e.setDisposable(this._scheduler.scheduleRecursiveWithRelativeAndState(0,this._period,t.bind(this))),e},e}();var _e,Oe=R;(function(){function t(){if(!D.postMessage||D.importScripts)return!1;var t=!1,e=D.onmessage;return D.onmessage=function(){t=!0},D.postMessage("","*"),D.onmessage=e,t}function e(t){if("string"==typeof t.data&&t.data.substring(0,o.length)===o){var e=t.data.substring(o.length),n=s[e];n(),delete s[e]}}var n=RegExp("^"+(G+"").replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/toString| for [^\]]+/g,".*?")+"$"),r="function"==typeof(r=_&&A&&_.setImmediate)&&!n.test(r)&&r,i="function"==typeof(i=_&&A&&_.clearImmediate)&&!n.test(i)&&i;if("undefined"!=typeof process&&"[object process]"==={}.toString.call(process))_e=process.nextTick;else if("function"==typeof r)_e=r,Oe=i;else if(t()){var o="ms.rx.schedule"+Math.random(),s={},u=0;D.addEventListener?D.addEventListener("message",e,!1):D.attachEvent("onmessage",e,!1),_e=function(t){var e=u++;s[e]=t,D.postMessage(o+e,"*")}}else if(D.MessageChannel){var c=new D.MessageChannel,a={},h=0;c.port1.onmessage=function(t){var e=t.data,n=a[e];n(),delete a[e]},_e=function(t){var e=h++;a[e]=t,c.port2.postMessage(e)}}else"document"in D&&"onreadystatechange"in D.document.createElement("script")?_e=function(t){var e=D.document.createElement("script");e.onreadystatechange=function(){t(),e.onreadystatechange=null,e.parentNode.removeChild(e),e=null},D.document.documentElement.appendChild(e)}:(_e=function(t){return setTimeout(t,0)},Oe=clearTimeout)})();var Re=De.timeout=function(){function t(t,e){var n=this,r=new Ee,i=_e(function(){r.isDisposed||r.setDisposable(e(n,t))});return new be(r,ye(function(){Oe(i)}))}function e(t,e,n){var r=this,i=De.normalize(e);if(0===i)return r.scheduleWithState(t,n);var o=new Ee,s=setTimeout(function(){o.isDisposed||o.setDisposable(n(r,t))},i);return new be(o,ye(function(){clearTimeout(s)}))}function n(t,e,n){return this.scheduleWithRelativeAndState(t,e-this.now(),n)}return new De(W,t,e,n)}(),je=O.Notification=function(){function t(t,e){this.hasValue=null==e?!1:e,this.kind=t}var e=t.prototype;return e.accept=function(t,e,n){return 1===arguments.length&&"object"==typeof t?this._acceptObservable(t):this._accept(t,e,n)},e.toObservable=function(t){var e=this;return t||(t=Ne),new dn(function(n){return t.schedule(function(){e._acceptObservable(n),"N"===e.kind&&n.onCompleted()})})},t}(),We=je.createOnNext=function(){function t(t){return t(this.value)}function e(t){return t.onNext(this.value)}function n(){return"OnNext("+this.value+")"}return function(r){var i=new je("N",!0);return i.value=r,i._accept=t,i._acceptObservable=e,i.toString=n,i}}(),ke=je.createOnError=function(){function t(t,e){return e(this.exception)}function e(t){return t.onError(this.exception)}function n(){return"OnError("+this.exception+")"}return function(r){var i=new je("E");return i.exception=r,i._accept=t,i._acceptObservable=e,i.toString=n,i}}(),qe=je.createOnCompleted=function(){function t(t,e,n){return n()}function e(t){return t.onCompleted()}function n(){return"OnCompleted()"}return function(){var r=new je("C");return r._accept=t,r._acceptObservable=e,r.toString=n,r}}(),Pe=O.internals.Enumerator=function(t){this._next=t};Pe.prototype.next=function(){return this._next()},Pe.prototype[z]=function(){return this};var Te=O.internals.Enumerable=function(t){this._iterator=t};Te.prototype[z]=function(){return this._iterator()},Te.prototype.concat=function(){var e=this;return new dn(function(n){var r;try{r=e[z]()}catch(i){return n.onError(),t}var o,s=new xe,u=Ne.scheduleRecursive(function(e){var i;if(!o){try{i=r.next()}catch(u){return n.onError(u),t}if(i.done)return n.onCompleted(),t;var c=i.value;T(c)&&(c=sn(c));var a=new Ee;s.setDisposable(a),a.setDisposable(c.subscribe(n.onNext.bind(n),n.onError.bind(n),function(){e()}))}});return new be(s,u,ye(function(){o=!0}))})},Te.prototype.catchException=function(){var e=this;return new dn(function(n){var r;try{r=e[z]()}catch(i){return n.onError(),t}var o,s,u=new xe,c=Ne.scheduleRecursive(function(e){if(!o){var i;try{i=r.next()}catch(c){return n.onError(c),t}if(i.done)return s?n.onError(s):n.onCompleted(),t;var a=i.value;T(a)&&(a=sn(a));var h=new Ee;u.setDisposable(h),h.setDisposable(a.subscribe(n.onNext.bind(n),function(t){s=t,e()},n.onCompleted.bind(n)))}});return new be(u,c,ye(function(){o=!0}))})};var Le=Te.repeat=function(t,e){return null==e&&(e=-1),new Te(function(){var n=e;return new Pe(function(){return 0===n?I:(n>0&&n--,{done:!1,value:t})})})},Ve=Te.forEach=function(t,e,n){return e||(e=j),new Te(function(){var r=-1;return new Pe(function(){return++r0&&(e=!this.isAcquired,this.isAcquired=!0),e&&this.disposable.setDisposable(this.scheduler.scheduleRecursive(function(e){var r;if(!(n.queue.length>0))return n.isAcquired=!1,t;r=n.queue.shift();try{r()}catch(i){throw n.queue=[],n.hasFaulted=!0,i}e()}))},n.prototype.dispose=function(){e.prototype.dispose.call(this),this.disposable.dispose()},n}(Fe);Ie.toArray=function(){var t=this;return new dn(function(e){var n=[];return t.subscribe(n.push.bind(n),e.onError.bind(e),function(){e.onNext(n),e.onCompleted()})})},Ue.create=Ue.createWithDisposable=function(t){return new dn(t)};var Qe=Ue.defer=function(t){return new dn(function(e){var n;try{n=t()}catch(r){return Xe(r).subscribe(e)}return T(n)&&(n=sn(n)),n.subscribe(e)})},$e=Ue.empty=function(t){return t||(t=Ne),new dn(function(e){return t.schedule(function(){e.onCompleted()})})},Ke=Ue.fromArray=function(t,e){return e||(e=Ae),new dn(function(n){var r=0,i=t.length;return e.scheduleRecursive(function(e){i>r?(n.onNext(t[r++]),e()):n.onCompleted()})})};Ue.fromIterable=function(e,n){return n||(n=Ae),new dn(function(r){var i;try{i=e[z]()}catch(o){return r.onError(o),t}return n.scheduleRecursive(function(e){var n;try{n=i.next()}catch(o){return r.onError(o),t}n.done?r.onCompleted():(r.onNext(n.value),e())})})},Ue.generate=function(e,n,r,i,o){return o||(o=Ae),new dn(function(s){var u=!0,c=e;return o.scheduleRecursive(function(e){var o,a;try{u?u=!1:c=r(c),o=n(c),o&&(a=i(c))}catch(h){return s.onError(h),t}o?(s.onNext(a),e()):s.onCompleted()})})};var Je=Ue.never=function(){return new dn(function(){return we})};Ue.of=function(){for(var t=arguments.length,e=Array(t),n=0;t>n;n++)e[n]=arguments[n];return Ke(e)},Ue.ofWithScheduler=function(t){for(var e=arguments.length-1,n=Array(e),r=0;e>r;r++)n[r]=arguments[r+1];return Ke(n,t)},Ue.range=function(t,e,n){return n||(n=Ae),new dn(function(r){return n.scheduleRecursiveWithState(0,function(n,i){e>n?(r.onNext(t+n),i(n+1)):r.onCompleted()})})},Ue.repeat=function(t,e,n){return n||(n=Ae),null==e&&(e=-1),Ze(t,n).repeat(e)};var Ze=Ue["return"]=Ue.returnValue=Ue.just=function(t,e){return e||(e=Ne),new dn(function(n){return e.schedule(function(){n.onNext(t),n.onCompleted()})})},Xe=Ue["throw"]=Ue.throwException=function(t,e){return e||(e=Ne),new dn(function(n){return e.schedule(function(){n.onError(t)})})};Ie["catch"]=Ie.catchException=function(t){return"function"==typeof t?f(this,t):Ge([this,t])};var Ge=Ue.catchException=Ue["catch"]=function(){var t=h(arguments,0);return Ve(t).catchException()};Ie.combineLatest=function(){var t=ae.call(arguments);return Array.isArray(t[0])?t[0].unshift(this):t.unshift(this),Ye.apply(this,t)};var Ye=Ue.combineLatest=function(){var e=ae.call(arguments),n=e.pop();return Array.isArray(e[0])&&(e=e[0]),new dn(function(r){function i(e){var i;if(c[e]=!0,a||(a=c.every(j))){try{i=n.apply(null,f)}catch(o){return r.onError(o),t}r.onNext(i)}else h.filter(function(t,n){return n!==e}).every(j)&&r.onCompleted()}function o(t){h[t]=!0,h.every(j)&&r.onCompleted()}for(var s=function(){return!1},u=e.length,c=l(u,s),a=!1,h=l(u,s),f=Array(u),p=Array(u),d=0;u>d;d++)(function(t){var n=e[t],s=new Ee;T(n)&&(n=sn(n)),s.setDisposable(n.subscribe(function(e){f[t]=e,i(t)},r.onError.bind(r),function(){o(t)})),p[t]=s})(d);return new be(p)})};Ie.concat=function(){var t=ae.call(arguments,0);return t.unshift(this),tn.apply(this,t)};var tn=Ue.concat=function(){var t=h(arguments,0);return Ve(t).concat()};Ie.concatObservable=Ie.concatAll=function(){return this.merge(1)},Ie.merge=function(t){if("number"!=typeof t)return en(this,t);var e=this;return new dn(function(n){var r=0,i=new be,o=!1,s=[],u=function(t){var e=new Ee;i.add(e),T(t)&&(t=sn(t)),e.setDisposable(t.subscribe(n.onNext.bind(n),n.onError.bind(n),function(){var t;i.remove(e),s.length>0?(t=s.shift(),u(t)):(r--,o&&0===r&&n.onCompleted())}))};return i.add(e.subscribe(function(e){t>r?(r++,u(e)):s.push(e)},n.onError.bind(n),function(){o=!0,0===r&&n.onCompleted()})),i})};var en=Ue.merge=function(){var t,e;return arguments[0]?arguments[0].now?(t=arguments[0],e=ae.call(arguments,1)):(t=Ne,e=ae.call(arguments,0)):(t=Ne,e=ae.call(arguments,1)),Array.isArray(e[0])&&(e=e[0]),Ke(e,t).mergeObservable()};Ie.mergeObservable=Ie.mergeAll=function(){var t=this;return new dn(function(e){var n=new be,r=!1,i=new Ee;return n.add(i),i.setDisposable(t.subscribe(function(t){var i=new Ee;n.add(i),T(t)&&(t=sn(t)),i.setDisposable(t.subscribe(function(t){e.onNext(t)},e.onError.bind(e),function(){n.remove(i),r&&1===n.length&&e.onCompleted()}))},e.onError.bind(e),function(){r=!0,1===n.length&&e.onCompleted()})),n})},Ie.skipUntil=function(t){var e=this;return new dn(function(n){var r=!1,i=new be(e.subscribe(function(t){r&&n.onNext(t)},n.onError.bind(n),function(){r&&n.onCompleted()}));T(t)&&(t=sn(t));var o=new Ee;return i.add(o),o.setDisposable(t.subscribe(function(){r=!0,o.dispose()},n.onError.bind(n),function(){o.dispose()})),i})},Ie["switch"]=Ie.switchLatest=function(){var t=this;return new dn(function(e){var n=!1,r=new xe,i=!1,o=0,s=t.subscribe(function(t){var s=new Ee,u=++o;n=!0,r.setDisposable(s),T(t)&&(t=sn(t)),s.setDisposable(t.subscribe(function(t){o===u&&e.onNext(t)},function(t){o===u&&e.onError(t)},function(){o===u&&(n=!1,i&&e.onCompleted())}))},e.onError.bind(e),function(){i=!0,n||e.onCompleted()});return new be(s,r)})},Ie.takeUntil=function(t){var e=this;return new dn(function(n){return T(t)&&(t=sn(t)),new be(e.subscribe(n),t.subscribe(n.onCompleted.bind(n),n.onError.bind(n),R))})},Ie.zip=function(){if(Array.isArray(arguments[0]))return p.apply(this,arguments);var e=this,n=ae.call(arguments),r=n.pop();return n.unshift(e),new dn(function(i){function o(n){var o,s;if(c.every(function(t){return t.length>0})){try{s=c.map(function(t){return t.shift()}),o=r.apply(e,s)}catch(u){return i.onError(u),t}i.onNext(o)}else a.filter(function(t,e){return e!==n}).every(j)&&i.onCompleted()}function s(t){a[t]=!0,a.every(function(t){return t})&&i.onCompleted()}for(var u=n.length,c=l(u,function(){return[]}),a=l(u,function(){return!1}),h=Array(u),f=0;u>f;f++)(function(t){var e=n[t],r=new Ee;T(e)&&(e=sn(e)),r.setDisposable(e.subscribe(function(e){c[t].push(e),o(t)},i.onError.bind(i),function(){s(t)})),h[t]=r})(f);return new be(h)})},Ue.zip=function(){var t=ae.call(arguments,0),e=t.shift();return e.zip.apply(e,t)},Ue.zipArray=function(){var e=h(arguments,0);return new dn(function(n){function r(e){if(s.every(function(t){return t.length>0})){var r=s.map(function(t){return t.shift()});n.onNext(r)}else if(u.filter(function(t,n){return n!==e}).every(j))return n.onCompleted(),t}function i(e){return u[e]=!0,u.every(j)?(n.onCompleted(),t):t}for(var o=e.length,s=l(o,function(){return[]}),u=l(o,function(){return!1}),c=Array(o),a=0;o>a;a++)(function(t){c[t]=new Ee,c[t].setDisposable(e[t].subscribe(function(e){s[t].push(e),r(t)},n.onError.bind(n),function(){i(t)}))})(a);var h=new be(c);return h.add(ye(function(){for(var t=0,e=s.length;e>t;t++)s[t]=[]})),h})},Ie.asObservable=function(){var t=this;return new dn(function(e){return t.subscribe(e)})},Ie.dematerialize=function(){var t=this;return new dn(function(e){return t.subscribe(function(t){return t.accept(e)},e.onError.bind(e),e.onCompleted.bind(e))})},Ie.distinctUntilChanged=function(e,n){var r=this;return e||(e=j),n||(n=k),new dn(function(i){var o,s=!1;return r.subscribe(function(r){var u,c=!1;try{u=e(r)}catch(a){return i.onError(a),t}if(s)try{c=n(o,u)}catch(a){return i.onError(a),t}s&&c||(s=!0,o=u,i.onNext(r))},i.onError.bind(i),i.onCompleted.bind(i))})},Ie["do"]=Ie.doAction=function(t,e,n){var r,i=this;return"function"==typeof t?r=t:(r=t.onNext.bind(t),e=t.onError.bind(t),n=t.onCompleted.bind(t)),new dn(function(t){return i.subscribe(function(e){try{r(e)}catch(n){t.onError(n)}t.onNext(e)},function(n){if(e){try{e(n)}catch(r){t.onError(r)}t.onError(n)}else t.onError(n)},function(){if(n){try{n()}catch(e){t.onError(e)}t.onCompleted()}else t.onCompleted()})})},Ie["finally"]=Ie.finallyAction=function(t){var e=this;return new dn(function(n){var r;try{r=e.subscribe(n)}catch(i){throw t(),i}return ye(function(){try{r.dispose()}catch(e){throw e}finally{t()}})})},Ie.ignoreElements=function(){var t=this;return new dn(function(e){return t.subscribe(R,e.onError.bind(e),e.onCompleted.bind(e))})},Ie.materialize=function(){var t=this;return new dn(function(e){return t.subscribe(function(t){e.onNext(We(t))},function(t){e.onNext(ke(t)),e.onCompleted()},function(){e.onNext(qe()),e.onCompleted()})})},Ie.repeat=function(t){return Le(this,t).concat()},Ie.retry=function(t){return Le(this,t).catchException()},Ie.scan=function(){var e,n,r=!1,i=this;return 2===arguments.length?(r=!0,e=arguments[0],n=arguments[1]):n=arguments[0],new dn(function(o){var s,u,c;return i.subscribe(function(i){try{c||(c=!0),s?u=n(u,i):(u=r?n(e,i):i,s=!0)}catch(a){return o.onError(a),t}o.onNext(u)},o.onError.bind(o),function(){!c&&r&&o.onNext(e),o.onCompleted()})})},Ie.skipLast=function(t){var e=this;return new dn(function(n){var r=[];return e.subscribe(function(e){r.push(e),r.length>t&&n.onNext(r.shift())},n.onError.bind(n),n.onCompleted.bind(n))})},Ie.startWith=function(){var t,e,n=0;return arguments.length&&"now"in Object(arguments[0])?(e=arguments[0],n=1):e=Ne,t=ae.call(arguments,n),Ve([Ke(t,e),this]).concat()},Ie.takeLast=function(t,e){return this.takeLastBuffer(t).selectMany(function(t){return Ke(t,e)})},Ie.takeLastBuffer=function(t){var e=this;return new dn(function(n){var r=[];return e.subscribe(function(e){r.push(e),r.length>t&&r.shift()},n.onError.bind(n),function(){n.onNext(r),n.onCompleted()})})},Ie.selectConcat=Ie.concatMap=function(t,e){return e?this.concatMap(function(n,r){var i=t(n,r),o=T(i)?sn(i):i;return o.map(function(t){return e(n,t,r)})}):"function"==typeof t?d.call(this,t):d.call(this,function(){return t})},Ie.select=Ie.map=function(e,n){var r=this;return new dn(function(i){var o=0;return r.subscribe(function(s){var u;try{u=e.call(n,s,o++,r)}catch(c){return i.onError(c),t}i.onNext(u)},i.onError.bind(i),i.onCompleted.bind(i))})},Ie.pluck=function(t){return this.select(function(e){return e[t]})},Ie.selectMany=Ie.flatMap=function(t,e){return e?this.selectMany(function(n,r){var i=t(n,r),o=T(i)?sn(i):i;return o.select(function(t){return e(n,t,r)})}):"function"==typeof t?b.call(this,t):b.call(this,function(){return t})},Ie.selectSwitch=Ie.flatMapLatest=Ie.switchMap=function(t,e){return this.select(t,e).switchLatest()},Ie.skip=function(t){if(0>t)throw Error(L);var e=this;return new dn(function(n){var r=t;return e.subscribe(function(t){0>=r?n.onNext(t):r--},n.onError.bind(n),n.onCompleted.bind(n)) +})},Ie.skipWhile=function(e,n){var r=this;return new dn(function(i){var o=0,s=!1;return r.subscribe(function(u){if(!s)try{s=!e.call(n,u,o++,r)}catch(c){return i.onError(c),t}s&&i.onNext(u)},i.onError.bind(i),i.onCompleted.bind(i))})},Ie.take=function(t,e){if(0>t)throw Error(L);if(0===t)return $e(e);var n=this;return new dn(function(e){var r=t;return n.subscribe(function(t){r>0&&(r--,e.onNext(t),0===r&&e.onCompleted())},e.onError.bind(e),e.onCompleted.bind(e))})},Ie.takeWhile=function(e,n){var r=this;return new dn(function(i){var o=0,s=!0;return r.subscribe(function(u){if(s){try{s=e.call(n,u,o++,r)}catch(c){return i.onError(c),t}s?i.onNext(u):i.onCompleted()}},i.onError.bind(i),i.onCompleted.bind(i))})},Ie.where=Ie.filter=function(e,n){var r=this;return new dn(function(i){var o=0;return r.subscribe(function(s){var u;try{u=e.call(n,s,o++,r)}catch(c){return i.onError(c),t}u&&i.onNext(s)},i.onError.bind(i),i.onCompleted.bind(i))})},Ue.fromCallback=function(e,n,r,i){return n||(n=Ne),function(){var o=ae.call(arguments,0);return new dn(function(s){return n.schedule(function(){function n(e){var n=e;if(i)try{n=i(arguments)}catch(r){return s.onError(r),t}else 1===n.length&&(n=n[0]);s.onNext(n),s.onCompleted()}o.push(n),e.apply(r,o)})})}},Ue.fromNodeCallback=function(e,n,r,i){return n||(n=Ne),function(){var o=ae.call(arguments,0);return new dn(function(s){return n.schedule(function(){function n(e){if(e)return s.onError(e),t;var n=ae.call(arguments,1);if(i)try{n=i(n)}catch(r){return s.onError(r),t}else 1===n.length&&(n=n[0]);s.onNext(n),s.onCompleted()}o.push(n),e.apply(r,o)})})}};var nn=D.angular&&angular.element?angular.element:D.jQuery?D.jQuery:D.Zepto?D.Zepto:null,rn=!!D.Ember&&"function"==typeof D.Ember.addListener;Ue.fromEvent=function(e,n,r){if(rn)return on(function(t){Ember.addListener(e,n,t)},function(t){Ember.removeListener(e,n,t)},r);if(nn){var i=nn(e);return on(function(t){i.on(n,t)},function(t){i.off(n,t)},r)}return new dn(function(i){return m(e,n,function(e){var n=e;if(r)try{n=r(arguments)}catch(o){return i.onError(o),t}i.onNext(n)})}).publish().refCount()};var on=Ue.fromEventPattern=function(e,n,r){return new dn(function(i){function o(e){var n=e;if(r)try{n=r(arguments)}catch(o){return i.onError(o),t}i.onNext(n)}var s=e(o);return ye(function(){n&&n(o,s)})}).publish().refCount()},sn=Ue.fromPromise=function(t){return new dn(function(e){return t.then(function(t){e.onNext(t),e.onCompleted()},function(t){e.onError(t)}),function(){t&&t.abort&&t.abort()}})};Ie.toPromise=function(t){if(t||(t=O.config.Promise),!t)throw Error("Promise type not provided nor in Rx.config.Promise");var e=this;return new t(function(t,n){var r,i=!1;e.subscribe(function(t){r=t,i=!0},function(t){n(t)},function(){i&&t(r)})})},Ue.startAsync=function(t){var e;try{e=t()}catch(n){return Xe(n)}return sn(e)},Ie.multicast=function(t,e){var n=this;return"function"==typeof t?new dn(function(r){var i=n.multicast(t());return new be(e(i).subscribe(r),i.connect())}):new un(n,t)},Ie.publish=function(t){return t?this.multicast(function(){return new mn},t):this.multicast(new mn)},Ie.share=function(){return this.publish(null).refCount()},Ie.publishLast=function(t){return t?this.multicast(function(){return new yn},t):this.multicast(new yn)},Ie.publishValue=function(t,e){return 2===arguments.length?this.multicast(function(){return new gn(e)},t):this.multicast(new gn(t))},Ie.shareValue=function(t){return this.publishValue(t).refCount()},Ie.replay=function(t,e,n,r){return t?this.multicast(function(){return new En(e,n,r)},t):this.multicast(new En(e,n,r))},Ie.shareReplay=function(t,e,n){return this.replay(null,t,e,n).refCount()};var un=O.ConnectableObservable=function(t){function e(e,n){function r(t){return i.subject.subscribe(t)}var i={subject:n,source:e.asObservable(),hasSubscription:!1,subscription:null};this.connect=function(){return i.hasSubscription||(i.hasSubscription=!0,i.subscription=new be(i.source.subscribe(i.subject),ye(function(){i.hasSubscription=!1}))),i.subscription},t.call(this,r)}return he(e,t),e.prototype.connect=function(){return this.connect()},e.prototype.refCount=function(){var t=null,e=0,n=this;return new dn(function(r){var i,o;return e++,i=1===e,o=n.subscribe(r),i&&(t=n.connect()),ye(function(){o.dispose(),e--,0===e&&t.dispose()})})},e}(Ue),cn=Ue.interval=function(t,e){return e||(e=Re),w(t,t,e)},an=Ue.timer=function(e,n,r){var i;return r||(r=Re),"number"==typeof n?i=n:"object"==typeof n&&"now"in n&&(r=n),i===t?y(e,r):w(e,i,r)};Ie.delay=function(t,e){e||(e=Re);var n=this;return new dn(function(r){var i,o=!1,s=new xe,u=null,c=[],a=!1;return i=n.materialize().timestamp(e).subscribe(function(n){var i,h;"E"===n.value.kind?(c=[],c.push(n),u=n.value.exception,h=!a):(c.push({value:n.value,timestamp:n.timestamp+t}),h=!o,o=!0),h&&(null!==u?r.onError(u):(i=new Ee,s.setDisposable(i),i.setDisposable(e.scheduleRecursiveWithRelative(t,function(t){var n,i,s,h;if(null===u){a=!0;do s=null,c.length>0&&0>=c[0].timestamp-e.now()&&(s=c.shift().value),null!==s&&s.accept(r);while(null!==s);h=!1,i=0,c.length>0?(h=!0,i=Math.max(0,c[0].timestamp-e.now())):o=!1,n=u,a=!1,null!==n?r.onError(n):h&&t(i)}}))))}),new be(i,s)})},Ie.throttle=function(t,e){return e||(e=Re),this.throttleWithSelector(function(){return an(t,e)})},Ie.timeInterval=function(t){var e=this;return t||(t=Re),Qe(function(){var n=t.now();return e.select(function(e){var r=t.now(),i=r-n;return n=r,{value:e,interval:i}})})},Ie.timestamp=function(t){return t||(t=Re),this.select(function(e){return{value:e,timestamp:t.now()}})},Ie.sample=function(t,e){return e||(e=Re),"number"==typeof t?E(this,cn(t,e)):E(this,t)},Ie.timeout=function(t,e,n){e||(e=Xe(Error("Timeout"))),n||(n=Re);var r=this,i=t instanceof Date?"scheduleWithAbsolute":"scheduleWithRelative";return new dn(function(o){var s=0,u=new Ee,c=new xe,a=!1,h=new xe;c.setDisposable(u);var l=function(){var r=s;h.setDisposable(n[i](t,function(){s===r&&(T(e)&&(e=sn(e)),c.setDisposable(e.subscribe(o)))}))};return l(),u.setDisposable(r.subscribe(function(t){a||(s++,o.onNext(t),l())},function(t){a||(s++,o.onError(t))},function(){a||(s++,o.onCompleted())})),new be(c,h)})},Ue.generateWithRelativeTime=function(e,n,r,i,o,s){return s||(s=Re),new dn(function(u){var c,a,h=!0,l=!1,f=e;return s.scheduleRecursiveWithRelative(0,function(e){l&&u.onNext(c);try{h?h=!1:f=r(f),l=n(f),l&&(c=i(f),a=o(f))}catch(s){return u.onError(s),t}l?e(a):u.onCompleted()})})},Ie.delaySubscription=function(t,e){return e||(e=Re),this.delayWithSelector(an(t,e),function(){return $e()})},Ie.delayWithSelector=function(e,n){var r,i,o=this;return"function"==typeof e?i=e:(r=e,i=n),new dn(function(e){var n=new be,s=!1,u=function(){s&&0===n.length&&e.onCompleted()},c=new xe,a=function(){c.setDisposable(o.subscribe(function(r){var o;try{o=i(r)}catch(s){return e.onError(s),t}var c=new Ee;n.add(c),c.setDisposable(o.subscribe(function(){e.onNext(r),n.remove(c),u()},e.onError.bind(e),function(){e.onNext(r),n.remove(c),u()}))},e.onError.bind(e),function(){s=!0,c.dispose(),u()}))};return r?c.setDisposable(r.subscribe(function(){a()},e.onError.bind(e),function(){a()})):a(),new be(c,n)})},Ie.timeoutWithSelector=function(e,n,r){if(1===arguments.length){n=e;var e=Je()}r||(r=Xe(Error("Timeout")));var i=this;return new dn(function(o){var s=new xe,u=new xe,c=new Ee;s.setDisposable(c);var a=0,h=!1,l=function(t){var e=a,n=function(){return a===e},i=new Ee;u.setDisposable(i),i.setDisposable(t.subscribe(function(){n()&&s.setDisposable(r.subscribe(o)),i.dispose()},function(t){n()&&o.onError(t)},function(){n()&&s.setDisposable(r.subscribe(o))}))};l(e);var f=function(){var t=!h;return t&&a++,t};return c.setDisposable(i.subscribe(function(e){if(f()){o.onNext(e);var r;try{r=n(e)}catch(i){return o.onError(i),t}l(r)}},function(t){f()&&o.onError(t)},function(){f()&&o.onCompleted()})),new be(s,u)})},Ie.throttleWithSelector=function(e){var n=this;return new dn(function(r){var i,o=!1,s=new xe,u=0,c=n.subscribe(function(n){var c;try{c=e(n)}catch(a){return r.onError(a),t}o=!0,i=n,u++;var h=u,l=new Ee;s.setDisposable(l),l.setDisposable(c.subscribe(function(){o&&u===h&&r.onNext(i),o=!1,l.dispose()},r.onError.bind(r),function(){o&&u===h&&r.onNext(i),o=!1,l.dispose()}))},function(t){s.dispose(),r.onError(t),o=!1,u++},function(){s.dispose(),o&&r.onNext(i),r.onCompleted(),o=!1,u++});return new be(c,s)})},Ie.skipLastWithTime=function(t,e){e||(e=Re);var n=this;return new dn(function(r){var i=[];return n.subscribe(function(n){var o=e.now();for(i.push({interval:o,value:n});i.length>0&&o-i[0].interval>=t;)r.onNext(i.shift().value)},r.onError.bind(r),function(){for(var n=e.now();i.length>0&&n-i[0].interval>=t;)r.onNext(i.shift().value);r.onCompleted()})})},Ie.takeLastWithTime=function(t,e,n){return this.takeLastBufferWithTime(t,e).selectMany(function(t){return Ke(t,n)})},Ie.takeLastBufferWithTime=function(t,e){var n=this;return e||(e=Re),new dn(function(r){var i=[];return n.subscribe(function(n){var r=e.now();for(i.push({interval:r,value:n});i.length>0&&r-i[0].interval>=t;)i.shift()},r.onError.bind(r),function(){for(var n=e.now(),o=[];i.length>0;){var s=i.shift();t>=n-s.interval&&o.push(s.value)}r.onNext(o),r.onCompleted()})})},Ie.takeWithTime=function(t,e){var n=this;return e||(e=Re),new dn(function(r){var i=e.scheduleWithRelative(t,function(){r.onCompleted()});return new be(i,n.subscribe(r))})},Ie.skipWithTime=function(t,e){var n=this;return e||(e=Re),new dn(function(r){var i=!1,o=e.scheduleWithRelative(t,function(){i=!0}),s=n.subscribe(function(t){i&&r.onNext(t)},r.onError.bind(r),r.onCompleted.bind(r));return new be(o,s)})},Ie.skipUntilWithTime=function(t,e){e||(e=Re);var n=this,r=t instanceof Date?"scheduleWithAbsolute":"scheduleWithRelative";return new dn(function(i){var o=!1;return new be(e[r](t,function(){o=!0}),n.subscribe(function(t){o&&i.onNext(t)},i.onError.bind(i),i.onCompleted.bind(i)))})},Ie.takeUntilWithTime=function(t,e){e||(e=Re);var n=this,r=t instanceof Date?"scheduleWithAbsolute":"scheduleWithRelative";return new dn(function(i){return new be(e[r](t,function(){i.onCompleted()}),n.subscribe(i))})};var hn=function(t){function e(t){var e=this.source.publish(),n=e.subscribe(t),r=we,i=this.subject.distinctUntilChanged().subscribe(function(t){t?r=e.connect():(r.dispose(),r=we)});return new be(n,r,i)}function n(n,r){this.source=n,this.subject=r||new mn,this.isPaused=!0,t.call(this,e)}return he(n,t),n.prototype.pause=function(){this.isPaused!==!0&&(this.isPaused=!0,this.subject.onNext(!1))},n.prototype.resume=function(){this.isPaused!==!1&&(this.isPaused=!1,this.subject.onNext(!0))},n}(Ue);Ie.pausable=function(t){return new hn(this,t)};var ln=function(t){function e(t){var e=[],n=!0,r=x(this.source,this.subject.distinctUntilChanged(),function(t,e){return{data:t,shouldFire:e}}).subscribe(function(r){if(r.shouldFire&&n&&t.onNext(r.data),r.shouldFire&&!n){for(;e.length>0;)t.onNext(e.shift());n=!0}else r.shouldFire||n?!r.shouldFire&&n&&(n=!1):e.push(r.data)},function(n){for(;e.length>0;)t.onNext(e.shift());t.onError(n)},function(){for(;e.length>0;)t.onNext(e.shift());t.onCompleted()});return this.subject.onNext(!1),r}function n(n,r){this.source=n,this.subject=r||new mn,this.isPaused=!0,t.call(this,e)}return he(n,t),n.prototype.pause=function(){this.isPaused!==!0&&(this.isPaused=!0,this.subject.onNext(!1))},n.prototype.resume=function(){this.isPaused!==!1&&(this.isPaused=!1,this.subject.onNext(!0))},n}(Ue);Ie.pausableBuffered=function(t){return new ln(this,t)},Ie.controlled=function(t){return null==t&&(t=!0),new fn(this,t)};var fn=function(t){function e(t){return this.source.subscribe(t)}function n(n,r){t.call(this,e),this.subject=new pn(r),this.source=n.multicast(this.subject).refCount()}return he(n,t),n.prototype.request=function(t){return null==t&&(t=-1),this.subject.request(t)},n}(Ue),pn=O.ControlledSubject=function(t){function n(t){return this.subject.subscribe(t)}function r(e){null==e&&(e=!0),t.call(this,n),this.subject=new mn,this.enableQueue=e,this.queue=e?[]:null,this.requestedCount=0,this.requestedDisposable=we,this.error=null,this.hasFailed=!1,this.hasCompleted=!1,this.controlledDisposable=we}return he(r,t),le(r.prototype,ze,{onCompleted:function(){e.call(this),this.hasCompleted=!0,this.enableQueue&&0!==this.queue.length||this.subject.onCompleted()},onError:function(t){e.call(this),this.hasFailed=!0,this.error=t,this.enableQueue&&0!==this.queue.length||this.subject.onError(t)},onNext:function(t){e.call(this);var n=!1;0===this.requestedCount?this.enableQueue&&this.queue.push(t):(-1!==this.requestedCount&&0===this.requestedCount--&&this.disposeCurrentRequest(),n=!0),n&&this.subject.onNext(t)},_processRequest:function(t){if(this.enableQueue){for(;this.queue.length>=t&&t>0;)this.subject.onNext(this.queue.shift()),t--;return 0!==this.queue.length?{numberOfItems:t,returnValue:!0}:{numberOfItems:t,returnValue:!1}}return this.hasFailed?(this.subject.onError(this.error),this.controlledDisposable.dispose(),this.controlledDisposable=we):this.hasCompleted&&(this.subject.onCompleted(),this.controlledDisposable.dispose(),this.controlledDisposable=we),{numberOfItems:t,returnValue:!1}},request:function(t){e.call(this),this.disposeCurrentRequest();var n=this,r=this._processRequest(t);return t=r.numberOfItems,r.returnValue?we:(this.requestedCount=t,this.requestedDisposable=ye(function(){n.requestedCount=0}),this.requestedDisposable)},disposeCurrentRequest:function(){this.requestedDisposable.dispose(),this.requestedDisposable=we},dispose:function(){this.isDisposed=!0,this.error=null,this.subject.dispose(),this.requestedDisposable.dispose()}}),r}(Ue);Ie.pairwise=function(){var t=this;return new dn(function(e){var n,r=!1;return t.subscribe(function(t){r?e.onNext([n,t]):r=!0,n=t},e.onError.bind(e),e.onCompleted.bind(e))})},Ie.partition=function(t,e){var n=this.publish().refCount();return[n.filter(t,e),n.filter(function(n,r,i){return!t.call(e,n,r,i)})]},Ie.exclusive=function(){var t=this;return new dn(function(e){var n=!1,r=!1,i=new Ee,o=new be;return o.add(i),i.setDisposable(t.subscribe(function(t){if(!n){n=!0,T(t)&&(t=sn(t));var i=new Ee;o.add(i),i.setDisposable(t.subscribe(e.onNext.bind(e),e.onError.bind(e),function(){o.remove(i),n=!1,r&&1===o.length&&e.onCompleted()}))}},e.onError.bind(e),function(){r=!0,n||1!==o.length||e.onCompleted()})),o})},Ie.exclusiveMap=function(e,n){var r=this;return new dn(function(i){var o=0,s=!1,u=!0,c=new Ee,a=new be;return a.add(c),c.setDisposable(r.subscribe(function(r){s||(s=!0,innerSubscription=new Ee,a.add(innerSubscription),T(r)&&(r=sn(r)),innerSubscription.setDisposable(r.subscribe(function(s){var u;try{u=e.call(n,s,o++,r)}catch(c){return i.onError(c),t}i.onNext(u)},i.onError.bind(i),function(){a.remove(innerSubscription),s=!1,u&&1===a.length&&i.onCompleted()})))},i.onError.bind(i),function(){u=!0,1!==a.length||s||i.onCompleted()})),a})};var dn=O.AnonymousObservable=function(e){function n(e){return e===t?e=we:"function"==typeof e&&(e=ye(e)),e}function r(i){function o(t){var e=function(){try{r.setDisposable(n(i(r)))}catch(t){if(!r.fail(t))throw t}},r=new bn(t);return Ae.scheduleRequired()?Ae.schedule(e):e(),r}return this instanceof r?(e.call(this,o),t):new r(i)}return he(r,e),r}(Ue),bn=function(t){function e(e){t.call(this),this.observer=e,this.m=new Ee}he(e,t);var n=e.prototype;return n.next=function(t){var e=!1;try{this.observer.onNext(t),e=!0}catch(n){throw n}finally{e||this.dispose()}},n.error=function(t){try{this.observer.onError(t)}catch(e){throw e}finally{this.dispose()}},n.completed=function(){try{this.observer.onCompleted()}catch(t){throw t}finally{this.dispose()}},n.setDisposable=function(t){this.m.setDisposable(t)},n.getDisposable=function(){return this.m.getDisposable()},n.disposable=function(t){return arguments.length?this.getDisposable():setDisposable(t)},n.dispose=function(){t.prototype.dispose.call(this),this.m.dispose()},e}(Fe),vn=function(t,e){this.subject=t,this.observer=e};vn.prototype.dispose=function(){if(!this.subject.isDisposed&&null!==this.observer){var t=this.subject.observers.indexOf(this.observer);this.subject.observers.splice(t,1),this.observer=null}};var mn=O.Subject=function(t){function n(t){return e.call(this),this.isStopped?this.exception?(t.onError(this.exception),we):(t.onCompleted(),we):(this.observers.push(t),new vn(this,t))}function r(){t.call(this,n),this.isDisposed=!1,this.isStopped=!1,this.observers=[]}return he(r,t),le(r.prototype,ze,{hasObservers:function(){return this.observers.length>0},onCompleted:function(){if(e.call(this),!this.isStopped){var t=this.observers.slice(0);this.isStopped=!0;for(var n=0,r=t.length;r>n;n++)t[n].onCompleted();this.observers=[]}},onError:function(t){if(e.call(this),!this.isStopped){var n=this.observers.slice(0);this.isStopped=!0,this.exception=t;for(var r=0,i=n.length;i>r;r++)n[r].onError(t);this.observers=[]}},onNext:function(t){if(e.call(this),!this.isStopped)for(var n=this.observers.slice(0),r=0,i=n.length;i>r;r++)n[r].onNext(t)},dispose:function(){this.isDisposed=!0,this.observers=null}}),r.create=function(t,e){return new wn(t,e)},r}(Ue),yn=O.AsyncSubject=function(t){function n(t){if(e.call(this),!this.isStopped)return this.observers.push(t),new vn(this,t);var n=this.exception,r=this.hasValue,i=this.value;return n?t.onError(n):r?(t.onNext(i),t.onCompleted()):t.onCompleted(),we}function r(){t.call(this,n),this.isDisposed=!1,this.isStopped=!1,this.value=null,this.hasValue=!1,this.observers=[],this.exception=null}return he(r,t),le(r.prototype,ze,{hasObservers:function(){return e.call(this),this.observers.length>0},onCompleted:function(){var t,n,r;if(e.call(this),!this.isStopped){this.isStopped=!0;var i=this.observers.slice(0),o=this.value,s=this.hasValue;if(s)for(n=0,r=i.length;r>n;n++)t=i[n],t.onNext(o),t.onCompleted();else for(n=0,r=i.length;r>n;n++)i[n].onCompleted();this.observers=[]}},onError:function(t){if(e.call(this),!this.isStopped){var n=this.observers.slice(0);this.isStopped=!0,this.exception=t;for(var r=0,i=n.length;i>r;r++)n[r].onError(t);this.observers=[]}},onNext:function(t){e.call(this),this.isStopped||(this.value=t,this.hasValue=!0)},dispose:function(){this.isDisposed=!0,this.observers=null,this.exception=null,this.value=null}}),r}(Ue),wn=function(t){function e(t){return this.observable.subscribe(t)}function n(n,r){t.call(this,e),this.observer=n,this.observable=r}return he(n,t),le(n.prototype,ze,{onCompleted:function(){this.observer.onCompleted()},onError:function(t){this.observer.onError(t)},onNext:function(t){this.observer.onNext(t)}}),n}(Ue),gn=O.BehaviorSubject=function(t){function n(t){if(e.call(this),!this.isStopped)return this.observers.push(t),t.onNext(this.value),new vn(this,t);var n=this.exception;return n?t.onError(n):t.onCompleted(),we}function r(e){t.call(this,n),this.value=e,this.observers=[],this.isDisposed=!1,this.isStopped=!1,this.exception=null}return he(r,t),le(r.prototype,ze,{hasObservers:function(){return this.observers.length>0},onCompleted:function(){if(e.call(this),!this.isStopped){var t=this.observers.slice(0);this.isStopped=!0;for(var n=0,r=t.length;r>n;n++)t[n].onCompleted();this.observers=[]}},onError:function(t){if(e.call(this),!this.isStopped){var n=this.observers.slice(0);this.isStopped=!0,this.exception=t;for(var r=0,i=n.length;i>r;r++)n[r].onError(t);this.observers=[]}},onNext:function(t){if(e.call(this),!this.isStopped){this.value=t;for(var n=this.observers.slice(0),r=0,i=n.length;i>r;r++)n[r].onNext(t)}},dispose:function(){this.isDisposed=!0,this.observers=null,this.value=null,this.exception=null}}),r}(Ue),En=O.ReplaySubject=function(t){function n(t,e){this.subject=t,this.observer=e}function r(t){var r=new He(this.scheduler,t),i=new n(this,r);e.call(this),this._trim(this.scheduler.now()),this.observers.push(r);for(var o=this.q.length,s=0,u=this.q.length;u>s;s++)r.onNext(this.q[s].value);return this.hasError?(o++,r.onError(this.error)):this.isStopped&&(o++,r.onCompleted()),r.ensureActive(o),i}function i(e,n,i){this.bufferSize=null==e?Number.MAX_VALUE:e,this.windowSize=null==n?Number.MAX_VALUE:n,this.scheduler=i||Ae,this.q=[],this.observers=[],this.isStopped=!1,this.isDisposed=!1,this.hasError=!1,this.error=null,t.call(this,r)}return n.prototype.dispose=function(){if(this.observer.dispose(),!this.subject.isDisposed){var t=this.subject.observers.indexOf(this.observer);this.subject.observers.splice(t,1)}},he(i,t),le(i.prototype,ze,{hasObservers:function(){return this.observers.length>0},_trim:function(t){for(;this.q.length>this.bufferSize;)this.q.shift();for(;this.q.length>0&&t-this.q[0].interval>this.windowSize;)this.q.shift()},onNext:function(t){var n;if(e.call(this),!this.isStopped){var r=this.scheduler.now();this.q.push({interval:r,value:t}),this._trim(r);for(var i=this.observers.slice(0),o=0,s=i.length;s>o;o++)n=i[o],n.onNext(t),n.ensureActive()}},onError:function(t){var n;if(e.call(this),!this.isStopped){this.isStopped=!0,this.error=t,this.hasError=!0;var r=this.scheduler.now();this._trim(r);for(var i=this.observers.slice(0),o=0,s=i.length;s>o;o++)n=i[o],n.onError(t),n.ensureActive();this.observers=[]}},onCompleted:function(){var t;if(e.call(this),!this.isStopped){this.isStopped=!0;var n=this.scheduler.now();this._trim(n);for(var r=this.observers.slice(0),i=0,o=r.length;o>i;i++)t=r[i],t.onCompleted(),t.ensureActive();this.observers=[]}},dispose:function(){this.isDisposed=!0,this.observers=null}}),i}(Ue);"function"==typeof define&&"object"==typeof define.amd&&define.amd?(D.Rx=O,define(function(){return O})):S&&N?A?(N.exports=O).Rx=O:S.Rx=O:D.Rx=O}).call(this); \ No newline at end of file diff --git a/ajax/libs/rxjs/2.2.28/rx.min.js b/ajax/libs/rxjs/2.2.28/rx.min.js new file mode 100644 index 000000000..bad2d52ff --- /dev/null +++ b/ajax/libs/rxjs/2.2.28/rx.min.js @@ -0,0 +1,2 @@ +(function(t){function e(){if(this.isDisposed)throw Error(k)}function n(t){var e=typeof t;return t&&("function"==e||"object"==e)||!1}function r(t){var e=[];if(!n(t))return e;ne.nonEnumArgs&&t.length&&u(t)&&(t=ie.call(t));var r=ne.enumPrototypes&&"function"==typeof t,i=ne.enumErrorProps&&(t===X||t instanceof Error);for(var o in t)r&&"prototype"==o||i&&("message"==o||"name"==o)||e.push(o);if(ne.nonEnumShadows&&t!==Z){var s=t.constructor,c=-1,a=te.length;if(t===(s&&s.prototype))var h=t===stringProto?Q:t===X?I:$.call(t),l=ee[h];for(;a>++c;)o=te[c],l&&l[o]||!K.call(t,o)||e.push(o)}return e}function i(t,e,n){for(var r=-1,i=n(t),o=i.length;o>++r;){var s=i[r];if(e(t[s],s,t)===!1)break}return t}function o(t,e){return i(t,e,r)}function s(t){return"function"!=typeof t.toString&&"string"==typeof(t+"")}function u(t){return t&&"object"==typeof t?$.call(t)==L:!1}function c(t){return"function"==typeof t||!1}function a(e,n,r,i){if(e===n)return 0!==e||1/e==1/n;var h=typeof e,l=typeof n;if(e===e&&(null==e||null==n||"function"!=h&&"object"!=h&&"function"!=l&&"object"!=l))return!1;var f=$.call(e),p=$.call(n);if(f==L&&(f=H),p==L&&(p=H),f!=p)return!1;switch(f){case z:case V:return+e==+n;case B:return e!=+e?n!=+n:0==e?1/e==1/n:e==+n;case U:case Q:return e==n+""}var d=f==M;if(!d){if(f!=H||!ne.nodeClass&&(s(e)||s(n)))return!1;var v=!ne.argsObject&&u(e)?Object:e.constructor,b=!ne.argsObject&&u(n)?Object:n.constructor;if(!(v==b||K.call(e,"constructor")&&K.call(n,"constructor")||c(v)&&v instanceof v&&c(b)&&b instanceof b||!("constructor"in e&&"constructor"in n)))return!1}r||(r=[]),i||(i=[]);for(var m=r.length;m--;)if(r[m]==e)return i[m]==n;var y=0;if(result=!0,r.push(e),i.push(n),d){if(m=e.length,y=n.length,result=y==m)for(;y--;){var w=n[y];if(!(result=a(e[y],w,r,i)))break}}else o(n,function(n,o,s){return K.call(s,o)?(y++,result=K.call(e,o)&&a(e[o],n,r,i)):t}),result&&o(e,function(e,n,r){return K.call(r,n)?result=--y>-1:t});return r.pop(),i.pop(),result}function h(t,e){return 1===t.length&&Array.isArray(t[e])?t[e]:ie.call(t)}function l(t,e){for(var n=Array(t),r=0;t>r;r++)n[r]=e();return n}function f(t,e){this.scheduler=t,this.disposable=e,this.isDisposed=!1}function p(e,n){return new nn(function(r){var i=new me,o=new ye;return o.setDisposable(i),i.setDisposable(e.subscribe(r.onNext.bind(r),function(e){var i,s;try{s=n(e)}catch(u){return r.onError(u),t}W(s)&&(s=Ue(s)),i=new me,o.setDisposable(i),i.setDisposable(s.subscribe(r))},r.onCompleted.bind(r))),o})}function d(e,n){var r=this;return new nn(function(i){var o=0,s=e.length;return r.subscribe(function(r){if(s>o){var u,c=e[o++];try{u=n(r,c)}catch(a){return i.onError(a),t}i.onNext(u)}else i.onCompleted()},i.onError.bind(i),i.onCompleted.bind(i))})}function v(t){return this.map(function(e,n){var r=t(e,n);return W(r)?Ue(r):r}).concatAll()}function b(t){return this.select(function(e,n){var r=t(e,n);return W(r)?Ue(r):r}).mergeObservable()}var m={"boolean":!1,"function":!0,object:!0,number:!1,string:!1,undefined:!1},y=m[typeof window]&&window||this,w=m[typeof exports]&&exports&&!exports.nodeType&&exports,g=m[typeof module]&&module&&!module.nodeType&&module,E=g&&g.exports===w&&w,x=m[typeof global]&&global;!x||x.global!==x&&x.window!==x||(y=x);var C={internals:{},config:{Promise:y.Promise},helpers:{}},D=C.helpers.noop=function(){},S=C.helpers.identity=function(t){return t},A=(C.helpers.pluck=function(t){return function(e){return e[t]}},C.helpers.just=function(t){return function(){return t}},C.helpers.defaultNow=Date.now),N=C.helpers.defaultComparer=function(t,e){return re(t,e)},_=C.helpers.defaultSubComparer=function(t,e){return t>e?1:e>t?-1:0},O=C.helpers.defaultKeySerializer=function(t){return""+t},R=C.helpers.defaultError=function(t){throw t},W=C.helpers.isPromise=function(t){return!!t&&"function"==typeof t.then&&t.then!==C.Observable.prototype.then};C.helpers.asArray=function(){return Array.prototype.slice.call(arguments)},C.helpers.not=function(t){return!t};var j="Argument out of range",k="Object has been disposed",q="object"==typeof Symbol&&Symbol.iterator||"_es6shim_iterator_";y.Set&&"function"==typeof(new y.Set)["@@iterator"]&&(q="@@iterator");var P,T={done:!0,value:t},L="[object Arguments]",M="[object Array]",z="[object Boolean]",V="[object Date]",I="[object Error]",F="[object Function]",B="[object Number]",H="[object Object]",U="[object RegExp]",Q="[object String]",$=Object.prototype.toString,K=Object.prototype.hasOwnProperty,J=$.call(arguments)==L,X=Error.prototype,Z=Object.prototype,G=Z.propertyIsEnumerable;try{P=!($.call(document)==H&&!({toString:0}+""))}catch(Y){P=!0}var te=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],ee={};ee[M]=ee[V]=ee[B]={constructor:!0,toLocaleString:!0,toString:!0,valueOf:!0},ee[z]=ee[Q]={constructor:!0,toString:!0,valueOf:!0},ee[I]=ee[F]=ee[U]={constructor:!0,toString:!0},ee[H]={constructor:!0};var ne={};(function(){var t=function(){this.x=1},e=[];t.prototype={valueOf:1,y:1};for(var n in new t)e.push(n);for(n in arguments);ne.enumErrorProps=G.call(X,"message")||G.call(X,"name"),ne.enumPrototypes=G.call(t,"prototype"),ne.nonEnumArgs=0!=n,ne.nonEnumShadows=!/valueOf/.test(e)})(1),J||(u=function(t){return t&&"object"==typeof t?K.call(t,"callee"):!1}),c(/x/)&&(c=function(t){return"function"==typeof t&&$.call(t)==F});var re=C.internals.isEqual=function(t,e){return a(t,e,[],[])},ie=Array.prototype.slice;({}).hasOwnProperty;var oe=this.inherits=C.internals.inherits=function(t,e){function n(){this.constructor=t}n.prototype=e.prototype,t.prototype=new n},se=C.internals.addProperties=function(t){for(var e=ie.call(arguments,1),n=0,r=e.length;r>n;n++){var i=e[n];for(var o in i)t[o]=i[o]}},ue=C.internals.addRef=function(t,e){return new nn(function(n){return new le(e.getDisposable(),t.subscribe(n))})},ce=function(t,e){this.id=t,this.value=e};ce.prototype.compareTo=function(t){var e=this.value.compareTo(t.value);return 0===e&&(e=this.id-t.id),e};var ae=C.internals.PriorityQueue=function(t){this.items=Array(t),this.length=0},he=ae.prototype;he.isHigherPriority=function(t,e){return 0>this.items[t].compareTo(this.items[e])},he.percolate=function(t){if(!(t>=this.length||0>t)){var e=t-1>>1;if(!(0>e||e===t)&&this.isHigherPriority(t,e)){var n=this.items[t];this.items[t]=this.items[e],this.items[e]=n,this.percolate(e)}}},he.heapify=function(e){if(e===t&&(e=0),!(e>=this.length||0>e)){var n=2*e+1,r=2*e+2,i=e;if(this.length>n&&this.isHigherPriority(n,i)&&(i=n),this.length>r&&this.isHigherPriority(r,i)&&(i=r),i!==e){var o=this.items[e];this.items[e]=this.items[i],this.items[i]=o,this.heapify(i)}}},he.peek=function(){return this.items[0].value},he.removeAt=function(t){this.items[t]=this.items[--this.length],delete this.items[this.length],this.heapify()},he.dequeue=function(){var t=this.peek();return this.removeAt(0),t},he.enqueue=function(t){var e=this.length++;this.items[e]=new ce(ae.count++,t),this.percolate(e)},he.remove=function(t){for(var e=0;this.length>e;e++)if(this.items[e].value===t)return this.removeAt(e),!0;return!1},ae.count=0;var le=C.CompositeDisposable=function(){this.disposables=h(arguments,0),this.isDisposed=!1,this.length=this.disposables.length},fe=le.prototype;fe.add=function(t){this.isDisposed?t.dispose():(this.disposables.push(t),this.length++)},fe.remove=function(t){var e=!1;if(!this.isDisposed){var n=this.disposables.indexOf(t);-1!==n&&(e=!0,this.disposables.splice(n,1),this.length--,t.dispose())}return e},fe.dispose=function(){if(!this.isDisposed){this.isDisposed=!0;var t=this.disposables.slice(0);this.disposables=[],this.length=0;for(var e=0,n=t.length;n>e;e++)t[e].dispose()}},fe.clear=function(){var t=this.disposables.slice(0);this.disposables=[],this.length=0;for(var e=0,n=t.length;n>e;e++)t[e].dispose()},fe.contains=function(t){return-1!==this.disposables.indexOf(t)},fe.toArray=function(){return this.disposables.slice(0)};var pe=C.Disposable=function(t){this.isDisposed=!1,this.action=t||D};pe.prototype.dispose=function(){this.isDisposed||(this.action(),this.isDisposed=!0)};var de=pe.create=function(t){return new pe(t)},ve=pe.empty={dispose:D},be=function(){function t(t){this.isSingle=t,this.isDisposed=!1,this.current=null}var e=t.prototype;return e.getDisposable=function(){return this.current},e.setDisposable=function(t){if(this.current&&this.isSingle)throw Error("Disposable has already been assigned");var e,n=this.isDisposed;n||(e=this.current,this.current=t),e&&e.dispose(),n&&t&&t.dispose()},e.dispose=function(){var t;this.isDisposed||(this.isDisposed=!0,t=this.current,this.current=null),t&&t.dispose()},t}(),me=C.SingleAssignmentDisposable=function(t){function e(){t.call(this,!0)}return oe(e,t),e}(be),ye=C.SerialDisposable=function(t){function e(){t.call(this,!1)}return oe(e,t),e}(be),we=C.RefCountDisposable=function(){function t(t){this.disposable=t,this.disposable.count++,this.isInnerDisposed=!1}function e(t){this.underlyingDisposable=t,this.isDisposed=!1,this.isPrimaryDisposed=!1,this.count=0}return t.prototype.dispose=function(){this.disposable.isDisposed||this.isInnerDisposed||(this.isInnerDisposed=!0,this.disposable.count--,0===this.disposable.count&&this.disposable.isPrimaryDisposed&&(this.disposable.isDisposed=!0,this.disposable.underlyingDisposable.dispose()))},e.prototype.dispose=function(){this.isDisposed||this.isPrimaryDisposed||(this.isPrimaryDisposed=!0,0===this.count&&(this.isDisposed=!0,this.underlyingDisposable.dispose()))},e.prototype.getDisposable=function(){return this.isDisposed?ve:new t(this)},e}();f.prototype.dispose=function(){var t=this;this.scheduler.schedule(function(){t.isDisposed||(t.isDisposed=!0,t.disposable.dispose())})};var ge=C.internals.ScheduledItem=function(t,e,n,r,i){this.scheduler=t,this.state=e,this.action=n,this.dueTime=r,this.comparer=i||_,this.disposable=new me};ge.prototype.invoke=function(){this.disposable.setDisposable(this.invokeCore())},ge.prototype.compareTo=function(t){return this.comparer(this.dueTime,t.dueTime)},ge.prototype.isCancelled=function(){return this.disposable.isDisposed},ge.prototype.invokeCore=function(){return this.action(this.scheduler,this.state)};var Ee=C.Scheduler=function(){function t(t,e,n,r){this.now=t,this._schedule=e,this._scheduleRelative=n,this._scheduleAbsolute=r}function e(t,e){var n=e.first,r=e.second,i=new le,o=function(e){r(e,function(e){var n=!1,r=!1,s=t.scheduleWithState(e,function(t,e){return n?i.remove(s):r=!0,o(e),ve});r||(i.add(s),n=!0)})};return o(n),i}function n(t,e,n){var r=e.first,i=e.second,o=new le,s=function(e){i(e,function(e,r){var i=!1,u=!1,c=t[n].call(t,e,r,function(t,e){return i?o.remove(c):u=!0,s(e),ve});u||(o.add(c),i=!0)})};return s(r),o}function r(t,e){return e(),ve}var i=t.prototype;return i.catchException=i["catch"]=function(t){return new Ne(this,t)},i.schedulePeriodic=function(t,e){return this.schedulePeriodicWithState(null,t,function(){e()})},i.schedulePeriodicWithState=function(t,e,n){var r=t,i=setInterval(function(){r=n(r)},e);return de(function(){clearInterval(i)})},i.schedule=function(t){return this._schedule(t,r)},i.scheduleWithState=function(t,e){return this._schedule(t,e)},i.scheduleWithRelative=function(t,e){return this._scheduleRelative(e,t,r)},i.scheduleWithRelativeAndState=function(t,e,n){return this._scheduleRelative(t,e,n)},i.scheduleWithAbsolute=function(t,e){return this._scheduleAbsolute(e,t,r)},i.scheduleWithAbsoluteAndState=function(t,e,n){return this._scheduleAbsolute(t,e,n)},i.scheduleRecursive=function(t){return this.scheduleRecursiveWithState(t,function(t,e){t(function(){e(t)})})},i.scheduleRecursiveWithState=function(t,n){return this.scheduleWithState({first:t,second:n},function(t,n){return e(t,n)})},i.scheduleRecursiveWithRelative=function(t,e){return this.scheduleRecursiveWithRelativeAndState(e,t,function(t,e){t(function(n){e(t,n)})})},i.scheduleRecursiveWithRelativeAndState=function(t,e,r){return this._scheduleRelative({first:t,second:r},e,function(t,e){return n(t,e,"scheduleWithRelativeAndState")})},i.scheduleRecursiveWithAbsolute=function(t,e){return this.scheduleRecursiveWithAbsoluteAndState(e,t,function(t,e){t(function(n){e(t,n)})})},i.scheduleRecursiveWithAbsoluteAndState=function(t,e,r){return this._scheduleAbsolute({first:t,second:r},e,function(t,e){return n(t,e,"scheduleWithAbsoluteAndState")})},t.now=A,t.normalize=function(t){return 0>t&&(t=0),t},t}(),xe=Ee.normalize;C.internals.SchedulePeriodicRecursive=function(){function t(t,e){e(0,this._period);try{this._state=this._action(this._state)}catch(n){throw this._cancel.dispose(),n}}function e(t,e,n,r){this._scheduler=t,this._state=e,this._period=n,this._action=r}return e.prototype.start=function(){var e=new me;return this._cancel=e,e.setDisposable(this._scheduler.scheduleRecursiveWithRelativeAndState(0,this._period,t.bind(this))),e},e}();var Ce,De=Ee.immediate=function(){function t(t,e){return e(this,t)}function e(t,e,n){for(var r=xe(r);r-this.now()>0;);return n(this,t)}function n(t,e,n){return this.scheduleWithRelativeAndState(t,e-this.now(),n)}return new Ee(A,t,e,n)}(),Se=Ee.currentThread=function(){function t(t){for(var e;t.length>0;)if(e=t.dequeue(),!e.isCancelled()){for(;e.dueTime-Ee.now()>0;);e.isCancelled()||e.invoke()}}function e(t,e){return this.scheduleWithRelativeAndState(t,0,e)}function n(e,n,r){var o=this.now()+Ee.normalize(n),s=new ge(this,e,r,o);if(i)i.enqueue(s);else{i=new ae(4),i.enqueue(s);try{t(i)}catch(u){throw u}finally{i=null}}return s.disposable}function r(t,e,n){return this.scheduleWithRelativeAndState(t,e-this.now(),n)}var i,o=new Ee(A,e,n,r);return o.scheduleRequired=function(){return null===i},o.ensureTrampoline=function(t){return null===i?this.schedule(t):t()},o}(),Ae=D;(function(){function t(){if(!y.postMessage||y.importScripts)return!1;var t=!1,e=y.onmessage;return y.onmessage=function(){t=!0},y.postMessage("","*"),y.onmessage=e,t}function e(t){if("string"==typeof t.data&&t.data.substring(0,o.length)===o){var e=t.data.substring(o.length),n=s[e];n(),delete s[e]}}var n=RegExp("^"+($+"").replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/toString| for [^\]]+/g,".*?")+"$"),r="function"==typeof(r=x&&E&&x.setImmediate)&&!n.test(r)&&r,i="function"==typeof(i=x&&E&&x.clearImmediate)&&!n.test(i)&&i;if("undefined"!=typeof process&&"[object process]"==={}.toString.call(process))Ce=process.nextTick;else if("function"==typeof r)Ce=r,Ae=i;else if(t()){var o="ms.rx.schedule"+Math.random(),s={},u=0;y.addEventListener?y.addEventListener("message",e,!1):y.attachEvent("onmessage",e,!1),Ce=function(t){var e=u++;s[e]=t,y.postMessage(o+e,"*")}}else if(y.MessageChannel){var c=new y.MessageChannel,a={},h=0;c.port1.onmessage=function(t){var e=t.data,n=a[e];n(),delete a[e]},Ce=function(t){var e=h++;a[e]=t,c.port2.postMessage(e)}}else"document"in y&&"onreadystatechange"in y.document.createElement("script")?Ce=function(t){var e=y.document.createElement("script");e.onreadystatechange=function(){t(),e.onreadystatechange=null,e.parentNode.removeChild(e),e=null},y.document.documentElement.appendChild(e)}:(Ce=function(t){return setTimeout(t,0)},Ae=clearTimeout)})(),Ee.timeout=function(){function t(t,e){var n=this,r=new me,i=Ce(function(){r.isDisposed||r.setDisposable(e(n,t))});return new le(r,de(function(){Ae(i)}))}function e(t,e,n){var r=this,i=Ee.normalize(e);if(0===i)return r.scheduleWithState(t,n);var o=new me,s=setTimeout(function(){o.isDisposed||o.setDisposable(n(r,t))},i);return new le(o,de(function(){clearTimeout(s)}))}function n(t,e,n){return this.scheduleWithRelativeAndState(t,e-this.now(),n)}return new Ee(A,t,e,n)}();var Ne=function(t){function e(){return this._scheduler.now()}function n(t,e){return this._scheduler.scheduleWithState(t,this._wrap(e))}function r(t,e,n){return this._scheduler.scheduleWithRelativeAndState(t,e,this._wrap(n))}function i(t,e,n){return this._scheduler.scheduleWithAbsoluteAndState(t,e,this._wrap(n))}function o(o,s){this._scheduler=o,this._handler=s,this._recursiveOriginal=null,this._recursiveWrapper=null,t.call(this,e,n,r,i)}return oe(o,t),o.prototype._clone=function(t){return new o(t,this._handler)},o.prototype._wrap=function(t){var e=this;return function(n,r){try{return t(e._getRecursiveWrapper(n),r)}catch(i){if(!e._handler(i))throw i;return ve}}},o.prototype._getRecursiveWrapper=function(t){if(this._recursiveOriginal!==t){this._recursiveOriginal=t;var e=this._clone(t);e._recursiveOriginal=t,e._recursiveWrapper=e,this._recursiveWrapper=e}return this._recursiveWrapper},o.prototype.schedulePeriodicWithState=function(t,e,n){var r=this,i=!1,o=new me;return o.setDisposable(this._scheduler.schedulePeriodicWithState(t,e,function(t){if(i)return null;try{return n(t)}catch(e){if(i=!0,!r._handler(e))throw e;return o.dispose(),null}})),o},o}(Ee),_e=C.Notification=function(){function t(t,e){this.hasValue=null==e?!1:e,this.kind=t}var e=t.prototype;return e.accept=function(t,e,n){return 1===arguments.length&&"object"==typeof t?this._acceptObservable(t):this._accept(t,e,n)},e.toObservable=function(t){var e=this;return t||(t=De),new nn(function(n){return t.schedule(function(){e._acceptObservable(n),"N"===e.kind&&n.onCompleted()})})},t}(),Oe=_e.createOnNext=function(){function t(t){return t(this.value)}function e(t){return t.onNext(this.value)}function n(){return"OnNext("+this.value+")"}return function(r){var i=new _e("N",!0);return i.value=r,i._accept=t,i._acceptObservable=e,i.toString=n,i}}(),Re=_e.createOnError=function(){function t(t,e){return e(this.exception)}function e(t){return t.onError(this.exception)}function n(){return"OnError("+this.exception+")"}return function(r){var i=new _e("E");return i.exception=r,i._accept=t,i._acceptObservable=e,i.toString=n,i}}(),We=_e.createOnCompleted=function(){function t(t,e,n){return n()}function e(t){return t.onCompleted()}function n(){return"OnCompleted()"}return function(){var r=new _e("C");return r._accept=t,r._acceptObservable=e,r.toString=n,r}}(),je=C.internals.Enumerator=function(t){this._next=t};je.prototype.next=function(){return this._next()},je.prototype[q]=function(){return this};var ke=C.internals.Enumerable=function(t){this._iterator=t};ke.prototype[q]=function(){return this._iterator()},ke.prototype.concat=function(){var e=this;return new nn(function(n){var r;try{r=e[q]()}catch(i){return n.onError(),t}var o,s=new ye,u=De.scheduleRecursive(function(e){var i;if(!o){try{i=r.next()}catch(u){return n.onError(u),t}if(i.done)return n.onCompleted(),t;var c=i.value;W(c)&&(c=Ue(c));var a=new me;s.setDisposable(a),a.setDisposable(c.subscribe(n.onNext.bind(n),n.onError.bind(n),function(){e()}))}});return new le(s,u,de(function(){o=!0}))})},ke.prototype.catchException=function(){var e=this;return new nn(function(n){var r;try{r=e[q]()}catch(i){return n.onError(),t}var o,s,u=new ye,c=De.scheduleRecursive(function(e){if(!o){var i;try{i=r.next()}catch(c){return n.onError(c),t}if(i.done)return s?n.onError(s):n.onCompleted(),t;var a=i.value;W(a)&&(a=Ue(a));var h=new me;u.setDisposable(h),h.setDisposable(a.subscribe(n.onNext.bind(n),function(t){s=t,e()},n.onCompleted.bind(n)))}});return new le(u,c,de(function(){o=!0}))})};var qe=ke.repeat=function(t,e){return null==e&&(e=-1),new ke(function(){var n=e;return new je(function(){return 0===n?T:(n>0&&n--,{done:!1,value:t})})})},Pe=ke.forEach=function(t,e,n){return e||(e=S),new ke(function(){var r=-1;return new je(function(){return++r0&&(e=!this.isAcquired,this.isAcquired=!0),e&&this.disposable.setDisposable(this.scheduler.scheduleRecursive(function(e){var r;if(!(n.queue.length>0))return n.isAcquired=!1,t;r=n.queue.shift();try{r()}catch(i){throw n.queue=[],n.hasFaulted=!0,i}e()}))},n.prototype.dispose=function(){e.prototype.dispose.call(this),this.disposable.dispose()},n}(ze),Be=function(t){function e(){t.apply(this,arguments)}return oe(e,t),e.prototype.next=function(e){t.prototype.next.call(this,e),this.ensureActive()},e.prototype.error=function(e){t.prototype.error.call(this,e),this.ensureActive()},e.prototype.completed=function(){t.prototype.completed.call(this),this.ensureActive()},e}(Fe),He=C.Observable=function(){function t(t){this._subscribe=t}return Me=t.prototype,Me.subscribe=Me.forEach=function(t,e,n){var r="object"==typeof t?t:Le(t,e,n);return this._subscribe(r)},t}();Me.observeOn=function(t){var e=this;return new nn(function(n){return e.subscribe(new Be(t,n))})},Me.subscribeOn=function(t){var e=this;return new nn(function(n){var r=new me,i=new ye;return i.setDisposable(r),r.setDisposable(t.schedule(function(){i.setDisposable(new f(t,e.subscribe(n)))})),i})};var Ue=He.fromPromise=function(t){return new nn(function(e){return t.then(function(t){e.onNext(t),e.onCompleted()},function(t){e.onError(t)}),function(){t&&t.abort&&t.abort()}})};Me.toPromise=function(t){if(t||(t=C.config.Promise),!t)throw Error("Promise type not provided nor in Rx.config.Promise");var e=this;return new t(function(t,n){var r,i=!1;e.subscribe(function(t){r=t,i=!0},function(t){n(t)},function(){i&&t(r)})})},Me.toArray=function(){var t=this;return new nn(function(e){var n=[];return t.subscribe(n.push.bind(n),e.onError.bind(e),function(){e.onNext(n),e.onCompleted()})})},He.create=He.createWithDisposable=function(t){return new nn(t)},He.defer=function(t){return new nn(function(e){var n;try{n=t()}catch(r){return Xe(r).subscribe(e)}return W(n)&&(n=Ue(n)),n.subscribe(e)})};var Qe=He.empty=function(t){return t||(t=De),new nn(function(e){return t.schedule(function(){e.onCompleted()})})},$e=He.fromArray=function(t,e){return e||(e=Se),new nn(function(n){var r=0,i=t.length;return e.scheduleRecursive(function(e){i>r?(n.onNext(t[r++]),e()):n.onCompleted()})})};He.fromIterable=function(e,n){return n||(n=Se),new nn(function(r){var i;try{i=e[q]()}catch(o){return r.onError(o),t}return n.scheduleRecursive(function(e){var n;try{n=i.next()}catch(o){return r.onError(o),t}n.done?r.onCompleted():(r.onNext(n.value),e())})})},He.generate=function(e,n,r,i,o){return o||(o=Se),new nn(function(s){var u=!0,c=e;return o.scheduleRecursive(function(e){var o,a;try{u?u=!1:c=r(c),o=n(c),o&&(a=i(c))}catch(h){return s.onError(h),t}o?(s.onNext(a),e()):s.onCompleted()})})};var Ke=He.never=function(){return new nn(function(){return ve})};He.of=function(){for(var t=arguments.length,e=Array(t),n=0;t>n;n++)e[n]=arguments[n];return $e(e)},He.ofWithScheduler=function(t){for(var e=arguments.length-1,n=Array(e),r=0;e>r;r++)n[r]=arguments[r+1];return $e(n,t)},He.range=function(t,e,n){return n||(n=Se),new nn(function(r){return n.scheduleRecursiveWithState(0,function(n,i){e>n?(r.onNext(t+n),i(n+1)):r.onCompleted()})})},He.repeat=function(t,e,n){return n||(n=Se),null==e&&(e=-1),Je(t,n).repeat(e)};var Je=He["return"]=He.returnValue=He.just=function(t,e){return e||(e=De),new nn(function(n){return e.schedule(function(){n.onNext(t),n.onCompleted()})})},Xe=He["throw"]=He.throwException=function(t,e){return e||(e=De),new nn(function(n){return e.schedule(function(){n.onError(t)})})};He.using=function(t,e){return new nn(function(n){var r,i,o=ve;try{r=t(),r&&(o=r),i=e(r)}catch(s){return new le(Xe(s).subscribe(n),o)}return new le(i.subscribe(n),o)})},Me.amb=function(t){var e=this;return new nn(function(n){function r(){o||(o=s,a.dispose())}function i(){o||(o=u,c.dispose())}var o,s="L",u="R",c=new me,a=new me;return W(t)&&(t=Ue(t)),c.setDisposable(e.subscribe(function(t){r(),o===s&&n.onNext(t)},function(t){r(),o===s&&n.onError(t)},function(){r(),o===s&&n.onCompleted()})),a.setDisposable(t.subscribe(function(t){i(),o===u&&n.onNext(t)},function(t){i(),o===u&&n.onError(t)},function(){i(),o===u&&n.onCompleted()})),new le(c,a)})},He.amb=function(){function t(t,e){return t.amb(e)}for(var e=Ke(),n=h(arguments,0),r=0,i=n.length;i>r;r++)e=t(e,n[r]);return e},Me["catch"]=Me.catchException=function(t){return"function"==typeof t?p(this,t):Ze([this,t])};var Ze=He.catchException=He["catch"]=function(){var t=h(arguments,0);return Pe(t).catchException()};Me.combineLatest=function(){var t=ie.call(arguments);return Array.isArray(t[0])?t[0].unshift(this):t.unshift(this),Ge.apply(this,t)};var Ge=He.combineLatest=function(){var e=ie.call(arguments),n=e.pop();return Array.isArray(e[0])&&(e=e[0]),new nn(function(r){function i(e){var i;if(c[e]=!0,a||(a=c.every(S))){try{i=n.apply(null,f)}catch(o){return r.onError(o),t}r.onNext(i)}else h.filter(function(t,n){return n!==e}).every(S)&&r.onCompleted()}function o(t){h[t]=!0,h.every(S)&&r.onCompleted()}for(var s=function(){return!1},u=e.length,c=l(u,s),a=!1,h=l(u,s),f=Array(u),p=Array(u),d=0;u>d;d++)(function(t){var n=e[t],s=new me;W(n)&&(n=Ue(n)),s.setDisposable(n.subscribe(function(e){f[t]=e,i(t)},r.onError.bind(r),function(){o(t)})),p[t]=s})(d);return new le(p)})};Me.concat=function(){var t=ie.call(arguments,0);return t.unshift(this),Ye.apply(this,t)};var Ye=He.concat=function(){var t=h(arguments,0);return Pe(t).concat()};Me.concatObservable=Me.concatAll=function(){return this.merge(1)},Me.merge=function(t){if("number"!=typeof t)return tn(this,t);var e=this;return new nn(function(n){var r=0,i=new le,o=!1,s=[],u=function(t){var e=new me;i.add(e),W(t)&&(t=Ue(t)),e.setDisposable(t.subscribe(n.onNext.bind(n),n.onError.bind(n),function(){var t;i.remove(e),s.length>0?(t=s.shift(),u(t)):(r--,o&&0===r&&n.onCompleted())}))};return i.add(e.subscribe(function(e){t>r?(r++,u(e)):s.push(e)},n.onError.bind(n),function(){o=!0,0===r&&n.onCompleted()})),i})};var tn=He.merge=function(){var t,e;return arguments[0]?arguments[0].now?(t=arguments[0],e=ie.call(arguments,1)):(t=De,e=ie.call(arguments,0)):(t=De,e=ie.call(arguments,1)),Array.isArray(e[0])&&(e=e[0]),$e(e,t).mergeObservable()};Me.mergeObservable=Me.mergeAll=function(){var t=this;return new nn(function(e){var n=new le,r=!1,i=new me;return n.add(i),i.setDisposable(t.subscribe(function(t){var i=new me;n.add(i),W(t)&&(t=Ue(t)),i.setDisposable(t.subscribe(function(t){e.onNext(t)},e.onError.bind(e),function(){n.remove(i),r&&1===n.length&&e.onCompleted()}))},e.onError.bind(e),function(){r=!0,1===n.length&&e.onCompleted()})),n})},Me.onErrorResumeNext=function(t){if(!t)throw Error("Second observable is required");return en([this,t])};var en=He.onErrorResumeNext=function(){var t=h(arguments,0);return new nn(function(e){var n=0,r=new ye,i=De.scheduleRecursive(function(i){var o,s;t.length>n?(o=t[n++],W(o)&&(o=Ue(o)),s=new me,r.setDisposable(s),s.setDisposable(o.subscribe(e.onNext.bind(e),function(){i()},function(){i()}))):e.onCompleted()});return new le(r,i)})};Me.skipUntil=function(t){var e=this;return new nn(function(n){var r=!1,i=new le(e.subscribe(function(t){r&&n.onNext(t)},n.onError.bind(n),function(){r&&n.onCompleted()}));W(t)&&(t=Ue(t));var o=new me;return i.add(o),o.setDisposable(t.subscribe(function(){r=!0,o.dispose()},n.onError.bind(n),function(){o.dispose()})),i})},Me["switch"]=Me.switchLatest=function(){var t=this;return new nn(function(e){var n=!1,r=new ye,i=!1,o=0,s=t.subscribe(function(t){var s=new me,u=++o;n=!0,r.setDisposable(s),W(t)&&(t=Ue(t)),s.setDisposable(t.subscribe(function(t){o===u&&e.onNext(t)},function(t){o===u&&e.onError(t)},function(){o===u&&(n=!1,i&&e.onCompleted())}))},e.onError.bind(e),function(){i=!0,n||e.onCompleted()});return new le(s,r)})},Me.takeUntil=function(t){var e=this;return new nn(function(n){return W(t)&&(t=Ue(t)),new le(e.subscribe(n),t.subscribe(n.onCompleted.bind(n),n.onError.bind(n),D))})},Me.zip=function(){if(Array.isArray(arguments[0]))return d.apply(this,arguments);var e=this,n=ie.call(arguments),r=n.pop();return n.unshift(e),new nn(function(i){function o(n){var o,s;if(c.every(function(t){return t.length>0})){try{s=c.map(function(t){return t.shift()}),o=r.apply(e,s)}catch(u){return i.onError(u),t}i.onNext(o)}else a.filter(function(t,e){return e!==n}).every(S)&&i.onCompleted()}function s(t){a[t]=!0,a.every(function(t){return t})&&i.onCompleted()}for(var u=n.length,c=l(u,function(){return[]}),a=l(u,function(){return!1}),h=Array(u),f=0;u>f;f++)(function(t){var e=n[t],r=new me;W(e)&&(e=Ue(e)),r.setDisposable(e.subscribe(function(e){c[t].push(e),o(t)},i.onError.bind(i),function(){s(t)})),h[t]=r})(f);return new le(h)})},He.zip=function(){var t=ie.call(arguments,0),e=t.shift();return e.zip.apply(e,t)},He.zipArray=function(){var e=h(arguments,0);return new nn(function(n){function r(e){if(s.every(function(t){return t.length>0})){var r=s.map(function(t){return t.shift()});n.onNext(r)}else if(u.filter(function(t,n){return n!==e}).every(S))return n.onCompleted(),t}function i(e){return u[e]=!0,u.every(S)?(n.onCompleted(),t):t}for(var o=e.length,s=l(o,function(){return[]}),u=l(o,function(){return!1}),c=Array(o),a=0;o>a;a++)(function(t){c[t]=new me,c[t].setDisposable(e[t].subscribe(function(e){s[t].push(e),r(t)},n.onError.bind(n),function(){i(t)}))})(a);var h=new le(c);return h.add(de(function(){for(var t=0,e=s.length;e>t;t++)s[t]=[]})),h})},Me.asObservable=function(){var t=this;return new nn(function(e){return t.subscribe(e)})},Me.bufferWithCount=function(t,e){return"number"!=typeof e&&(e=t),this.windowWithCount(t,e).selectMany(function(t){return t.toArray()}).where(function(t){return t.length>0})},Me.dematerialize=function(){var t=this;return new nn(function(e){return t.subscribe(function(t){return t.accept(e)},e.onError.bind(e),e.onCompleted.bind(e))})},Me.distinctUntilChanged=function(e,n){var r=this;return e||(e=S),n||(n=N),new nn(function(i){var o,s=!1;return r.subscribe(function(r){var u,c=!1;try{u=e(r)}catch(a){return i.onError(a),t}if(s)try{c=n(o,u)}catch(a){return i.onError(a),t}s&&c||(s=!0,o=u,i.onNext(r))},i.onError.bind(i),i.onCompleted.bind(i))})},Me["do"]=Me.doAction=function(t,e,n){var r,i=this; +return"function"==typeof t?r=t:(r=t.onNext.bind(t),e=t.onError.bind(t),n=t.onCompleted.bind(t)),new nn(function(t){return i.subscribe(function(e){try{r(e)}catch(n){t.onError(n)}t.onNext(e)},function(n){if(e){try{e(n)}catch(r){t.onError(r)}t.onError(n)}else t.onError(n)},function(){if(n){try{n()}catch(e){t.onError(e)}t.onCompleted()}else t.onCompleted()})})},Me["finally"]=Me.finallyAction=function(t){var e=this;return new nn(function(n){var r;try{r=e.subscribe(n)}catch(i){throw t(),i}return de(function(){try{r.dispose()}catch(e){throw e}finally{t()}})})},Me.ignoreElements=function(){var t=this;return new nn(function(e){return t.subscribe(D,e.onError.bind(e),e.onCompleted.bind(e))})},Me.materialize=function(){var t=this;return new nn(function(e){return t.subscribe(function(t){e.onNext(Oe(t))},function(t){e.onNext(Re(t)),e.onCompleted()},function(){e.onNext(We()),e.onCompleted()})})},Me.repeat=function(t){return qe(this,t).concat()},Me.retry=function(t){return qe(this,t).catchException()},Me.scan=function(){var e,n,r=!1,i=this;return 2===arguments.length?(r=!0,e=arguments[0],n=arguments[1]):n=arguments[0],new nn(function(o){var s,u,c;return i.subscribe(function(i){try{c||(c=!0),s?u=n(u,i):(u=r?n(e,i):i,s=!0)}catch(a){return o.onError(a),t}o.onNext(u)},o.onError.bind(o),function(){!c&&r&&o.onNext(e),o.onCompleted()})})},Me.skipLast=function(t){var e=this;return new nn(function(n){var r=[];return e.subscribe(function(e){r.push(e),r.length>t&&n.onNext(r.shift())},n.onError.bind(n),n.onCompleted.bind(n))})},Me.startWith=function(){var t,e,n=0;return arguments.length&&"now"in Object(arguments[0])?(e=arguments[0],n=1):e=De,t=ie.call(arguments,n),Pe([$e(t,e),this]).concat()},Me.takeLast=function(t,e){return this.takeLastBuffer(t).selectMany(function(t){return $e(t,e)})},Me.takeLastBuffer=function(t){var e=this;return new nn(function(n){var r=[];return e.subscribe(function(e){r.push(e),r.length>t&&r.shift()},n.onError.bind(n),function(){n.onNext(r),n.onCompleted()})})},Me.windowWithCount=function(t,e){var n=this;if(0>=t)throw Error(j);if(1===arguments.length&&(e=t),0>=e)throw Error(j);return new nn(function(r){var i=new me,o=new we(i),s=0,u=[],c=function(){var t=new un;u.push(t),r.onNext(ue(t,o))};return c(),i.setDisposable(n.subscribe(function(n){for(var r,i=0,o=u.length;o>i;i++)u[i].onNext(n);var a=s-t+1;a>=0&&0===a%e&&(r=u.shift(),r.onCompleted()),s++,0===s%e&&c()},function(t){for(;u.length>0;)u.shift().onError(t);r.onError(t)},function(){for(;u.length>0;)u.shift().onCompleted();r.onCompleted()})),o})},Me.selectConcat=Me.concatMap=function(t,e){return e?this.concatMap(function(n,r){var i=t(n,r),o=W(i)?Ue(i):i;return o.map(function(t){return e(n,t,r)})}):"function"==typeof t?v.call(this,t):v.call(this,function(){return t})},Me.defaultIfEmpty=function(e){var n=this;return e===t&&(e=null),new nn(function(t){var r=!1;return n.subscribe(function(e){r=!0,t.onNext(e)},t.onError.bind(t),function(){r||t.onNext(e),t.onCompleted()})})},Me.distinct=function(e,n){var r=this;return e||(e=S),n||(n=O),new nn(function(i){var o={};return r.subscribe(function(r){var s,u,c,a=!1;try{s=e(r),u=n(s)}catch(h){return i.onError(h),t}for(c in o)if(u===c){a=!0;break}a||(o[u]=null,i.onNext(r))},i.onError.bind(i),i.onCompleted.bind(i))})},Me.groupBy=function(t,e,n){return this.groupByUntil(t,e,function(){return Ke()},n)},Me.groupByUntil=function(e,n,r,i){var o=this;return n||(n=S),i||(i=O),new nn(function(s){var u={},c=new le,a=new we(c);return c.add(o.subscribe(function(o){var h,l,f,p,d,v,b,m,y,w;try{v=e(o),b=i(v)}catch(g){for(w in u)u[w].onError(g);return s.onError(g),t}p=!1;try{y=u[b],y||(y=new un,u[b]=y,p=!0)}catch(g){for(w in u)u[w].onError(g);return s.onError(g),t}if(p){d=new on(v,y,a),l=new on(v,y);try{h=r(l)}catch(g){for(w in u)u[w].onError(g);return s.onError(g),t}s.onNext(d),m=new me,c.add(m);var E=function(){b in u&&(delete u[b],y.onCompleted()),c.remove(m)};m.setDisposable(h.take(1).subscribe(D,function(t){for(w in u)u[w].onError(t);s.onError(t)},function(){E()}))}try{f=n(o)}catch(g){for(w in u)u[w].onError(g);return s.onError(g),t}y.onNext(f)},function(t){for(var e in u)u[e].onError(t);s.onError(t)},function(){for(var t in u)u[t].onCompleted();s.onCompleted()})),a})},Me.select=Me.map=function(e,n){var r=this;return new nn(function(i){var o=0;return r.subscribe(function(s){var u;try{u=e.call(n,s,o++,r)}catch(c){return i.onError(c),t}i.onNext(u)},i.onError.bind(i),i.onCompleted.bind(i))})},Me.pluck=function(t){return this.select(function(e){return e[t]})},Me.selectMany=Me.flatMap=function(t,e){return e?this.selectMany(function(n,r){var i=t(n,r),o=W(i)?Ue(i):i;return o.select(function(t){return e(n,t,r)})}):"function"==typeof t?b.call(this,t):b.call(this,function(){return t})},Me.selectSwitch=Me.flatMapLatest=Me.switchMap=function(t,e){return this.select(t,e).switchLatest()},Me.skip=function(t){if(0>t)throw Error(j);var e=this;return new nn(function(n){var r=t;return e.subscribe(function(t){0>=r?n.onNext(t):r--},n.onError.bind(n),n.onCompleted.bind(n))})},Me.skipWhile=function(e,n){var r=this;return new nn(function(i){var o=0,s=!1;return r.subscribe(function(u){if(!s)try{s=!e.call(n,u,o++,r)}catch(c){return i.onError(c),t}s&&i.onNext(u)},i.onError.bind(i),i.onCompleted.bind(i))})},Me.take=function(t,e){if(0>t)throw Error(j);if(0===t)return Qe(e);var n=this;return new nn(function(e){var r=t;return n.subscribe(function(t){r>0&&(r--,e.onNext(t),0===r&&e.onCompleted())},e.onError.bind(e),e.onCompleted.bind(e))})},Me.takeWhile=function(e,n){var r=this;return new nn(function(i){var o=0,s=!0;return r.subscribe(function(u){if(s){try{s=e.call(n,u,o++,r)}catch(c){return i.onError(c),t}s?i.onNext(u):i.onCompleted()}},i.onError.bind(i),i.onCompleted.bind(i))})},Me.where=Me.filter=function(e,n){var r=this;return new nn(function(i){var o=0;return r.subscribe(function(s){var u;try{u=e.call(n,s,o++,r)}catch(c){return i.onError(c),t}u&&i.onNext(s)},i.onError.bind(i),i.onCompleted.bind(i))})},Me.exclusive=function(){var t=this;return new nn(function(e){var n=!1,r=!1,i=new me,o=new le;return o.add(i),i.setDisposable(t.subscribe(function(t){if(!n){n=!0,W(t)&&(t=Ue(t));var i=new me;o.add(i),i.setDisposable(t.subscribe(e.onNext.bind(e),e.onError.bind(e),function(){o.remove(i),n=!1,r&&1===o.length&&e.onCompleted()}))}},e.onError.bind(e),function(){r=!0,n||1!==o.length||e.onCompleted()})),o})},Me.exclusiveMap=function(e,n){var r=this;return new nn(function(i){var o=0,s=!1,u=!0,c=new me,a=new le;return a.add(c),c.setDisposable(r.subscribe(function(r){s||(s=!0,innerSubscription=new me,a.add(innerSubscription),W(r)&&(r=Ue(r)),innerSubscription.setDisposable(r.subscribe(function(s){var u;try{u=e.call(n,s,o++,r)}catch(c){return i.onError(c),t}i.onNext(u)},i.onError.bind(i),function(){a.remove(innerSubscription),s=!1,u&&1===a.length&&i.onCompleted()})))},i.onError.bind(i),function(){u=!0,1!==a.length||s||i.onCompleted()})),a})};var nn=C.AnonymousObservable=function(e){function n(e){return e===t?e=ve:"function"==typeof e&&(e=de(e)),e}function r(i){function o(t){var e=function(){try{r.setDisposable(n(i(r)))}catch(t){if(!r.fail(t))throw t}},r=new rn(t);return Se.scheduleRequired()?Se.schedule(e):e(),r}return this instanceof r?(e.call(this,o),t):new r(i)}return oe(r,e),r}(He),rn=function(t){function e(e){t.call(this),this.observer=e,this.m=new me}oe(e,t);var n=e.prototype;return n.next=function(t){var e=!1;try{this.observer.onNext(t),e=!0}catch(n){throw n}finally{e||this.dispose()}},n.error=function(t){try{this.observer.onError(t)}catch(e){throw e}finally{this.dispose()}},n.completed=function(){try{this.observer.onCompleted()}catch(t){throw t}finally{this.dispose()}},n.setDisposable=function(t){this.m.setDisposable(t)},n.getDisposable=function(){return this.m.getDisposable()},n.disposable=function(t){return arguments.length?this.getDisposable():setDisposable(t)},n.dispose=function(){t.prototype.dispose.call(this),this.m.dispose()},e}(ze),on=function(t){function e(t){return this.underlyingObservable.subscribe(t)}function n(n,r,i){t.call(this,e),this.key=n,this.underlyingObservable=i?new nn(function(t){return new le(i.getDisposable(),r.subscribe(t))}):r}return oe(n,t),n}(He),sn=function(t,e){this.subject=t,this.observer=e};sn.prototype.dispose=function(){if(!this.subject.isDisposed&&null!==this.observer){var t=this.subject.observers.indexOf(this.observer);this.subject.observers.splice(t,1),this.observer=null}};var un=C.Subject=function(t){function n(t){return e.call(this),this.isStopped?this.exception?(t.onError(this.exception),ve):(t.onCompleted(),ve):(this.observers.push(t),new sn(this,t))}function r(){t.call(this,n),this.isDisposed=!1,this.isStopped=!1,this.observers=[]}return oe(r,t),se(r.prototype,Te,{hasObservers:function(){return this.observers.length>0},onCompleted:function(){if(e.call(this),!this.isStopped){var t=this.observers.slice(0);this.isStopped=!0;for(var n=0,r=t.length;r>n;n++)t[n].onCompleted();this.observers=[]}},onError:function(t){if(e.call(this),!this.isStopped){var n=this.observers.slice(0);this.isStopped=!0,this.exception=t;for(var r=0,i=n.length;i>r;r++)n[r].onError(t);this.observers=[]}},onNext:function(t){if(e.call(this),!this.isStopped)for(var n=this.observers.slice(0),r=0,i=n.length;i>r;r++)n[r].onNext(t)},dispose:function(){this.isDisposed=!0,this.observers=null}}),r.create=function(t,e){return new cn(t,e)},r}(He);C.AsyncSubject=function(t){function n(t){if(e.call(this),!this.isStopped)return this.observers.push(t),new sn(this,t);var n=this.exception,r=this.hasValue,i=this.value;return n?t.onError(n):r?(t.onNext(i),t.onCompleted()):t.onCompleted(),ve}function r(){t.call(this,n),this.isDisposed=!1,this.isStopped=!1,this.value=null,this.hasValue=!1,this.observers=[],this.exception=null}return oe(r,t),se(r.prototype,Te,{hasObservers:function(){return e.call(this),this.observers.length>0},onCompleted:function(){var t,n,r;if(e.call(this),!this.isStopped){this.isStopped=!0;var i=this.observers.slice(0),o=this.value,s=this.hasValue;if(s)for(n=0,r=i.length;r>n;n++)t=i[n],t.onNext(o),t.onCompleted();else for(n=0,r=i.length;r>n;n++)i[n].onCompleted();this.observers=[]}},onError:function(t){if(e.call(this),!this.isStopped){var n=this.observers.slice(0);this.isStopped=!0,this.exception=t;for(var r=0,i=n.length;i>r;r++)n[r].onError(t);this.observers=[]}},onNext:function(t){e.call(this),this.isStopped||(this.value=t,this.hasValue=!0)},dispose:function(){this.isDisposed=!0,this.observers=null,this.exception=null,this.value=null}}),r}(He);var cn=function(t){function e(t){return this.observable.subscribe(t)}function n(n,r){t.call(this,e),this.observer=n,this.observable=r}return oe(n,t),se(n.prototype,Te,{onCompleted:function(){this.observer.onCompleted()},onError:function(t){this.observer.onError(t)},onNext:function(t){this.observer.onNext(t)}}),n}(He);"function"==typeof define&&"object"==typeof define.amd&&define.amd?(y.Rx=C,define(function(){return C})):w&&g?E?(g.exports=C).Rx=C:w.Rx=C:y.Rx=C}).call(this); \ No newline at end of file diff --git a/ajax/libs/rxjs/2.2.28/rx.testing.js b/ajax/libs/rxjs/2.2.28/rx.testing.js new file mode 100644 index 000000000..0dc3720e4 --- /dev/null +++ b/ajax/libs/rxjs/2.2.28/rx.testing.js @@ -0,0 +1,500 @@ +// 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 (typeof define === 'function' && define.amd) { + define(['rx.virtualtime', 'exports'], function (Rx, exports) { + root.Rx = factory(root, exports, Rx); + return root.Rx; + }); + } else if (typeof module === 'object' && module && module.exports === freeExports) { + module.exports = factory(root, module.exports, require('./rx.all')); + } 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, + slice = Array.prototype.slice, + inherits = Rx.internals.inherits, + defaultComparer = Rx.internals.isEqual; + + function argsOrArray(args, idx) { + return args.length === 1 && Array.isArray(args[idx]) ? + args[idx] : + slice.call(args); + } + + /** + * @private + * @constructor + */ + function OnNextPredicate(predicate) { + this.predicate = predicate; + }; + + /** + * @private + * @memberOf OnNextPredicate# + */ + 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); + }; + + /** + * @private + * @constructor + */ + function OnErrorPredicate(predicate) { + this.predicate = predicate; + }; + + /** + * @private + * @memberOf OnErrorPredicate# + */ + 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); + }; + + /** + * @static + * type Object + */ + 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) { + if (typeof value === 'function') { + return new Recorded(ticks, new OnNextPredicate(value)); + } + return 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, exception) { + if (typeof exception === 'function') { + return new Recorded(ticks, new OnErrorPredicate(exception)); + } + return new Recorded(ticks, Notification.createOnError(exception)); + }, + /** + * 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 + ')'; + }; + + /** @private */ + var MockDisposable = Rx.MockDisposable = function (scheduler) { + this.scheduler = scheduler; + this.disposes = []; + this.disposes.push(this.scheduler.clock); + }; + + /* + * @memberOf MockDisposable# + * @prviate + */ + MockDisposable.prototype.dispose = function () { + this.disposes.push(this.scheduler.clock); + }; + + /** @private */ + var MockObserver = (function (_super) { + inherits(MockObserver, _super); + + /* + * @constructor + * @prviate + */ + function MockObserver(scheduler) { + _super.call(this); + this.scheduler = scheduler; + this.messages = []; + } + + var MockObserverPrototype = MockObserver.prototype; + + /* + * @memberOf MockObserverPrototype# + * @prviate + */ + MockObserverPrototype.onNext = function (value) { + this.messages.push(new Recorded(this.scheduler.clock, Notification.createOnNext(value))); + }; + + /* + * @memberOf MockObserverPrototype# + * @prviate + */ + MockObserverPrototype.onError = function (exception) { + this.messages.push(new Recorded(this.scheduler.clock, Notification.createOnError(exception))); + }; + + /* + * @memberOf MockObserverPrototype# + * @prviate + */ + MockObserverPrototype.onCompleted = function () { + this.messages.push(new Recorded(this.scheduler.clock, Notification.createOnCompleted())); + }; + + return MockObserver; + })(Observer); + + /** @private */ + 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); + + /** + * @private + * @constructor + */ + 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); + + /** @private */ + 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); + + /** + * @private + * @constructor + */ + 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); + } + + /** @constructor */ + 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) { + if (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 messages = argsOrArray(arguments, 0); + return new HotObservable(this, messages); + }; + /** + * 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 messages = argsOrArray(arguments, 0); + return new ColdObservable(this, messages); + }; + /** + * 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; +})); \ No newline at end of file diff --git a/ajax/libs/rxjs/2.2.28/rx.testing.min.js b/ajax/libs/rxjs/2.2.28/rx.testing.min.js new file mode 100644 index 000000000..9f0b63bb6 --- /dev/null +++ b/ajax/libs/rxjs/2.2.28/rx.testing.min.js @@ -0,0 +1 @@ +(function(t){var e={"boolean":!1,"function":!0,object:!0,number:!1,string:!1,undefined:!1},n=e[typeof window]&&window||this,r=e[typeof exports]&&exports&&!exports.nodeType&&exports,i=e[typeof module]&&module&&!module.nodeType&&module,o=(i&&i.exports===r&&r,e[typeof global]&&global);!o||o.global!==o&&o.window!==o||(n=o),"function"==typeof define&&define.amd?define(["rx.virtualtime","exports"],function(e,r){return n.Rx=t(n,r,e),n.Rx}):"object"==typeof module&&module&&module.exports===r?module.exports=t(n,module.exports,require("./rx.all")):n.Rx=t(n,{},n.Rx)}).call(this,function(t,e,n){function r(t,e){return 1===t.length&&Array.isArray(t[e])?t[e]:d.call(t)}function i(t){this.predicate=t}function o(t){this.predicate=t}var s=n.Observer,u=n.Observable,c=n.Notification,a=n.VirtualTimeScheduler,h=n.Disposable,l=h.empty,f=h.create,p=n.CompositeDisposable,d=(n.SingleAssignmentDisposable,Array.prototype.slice),b=n.internals.inherits,v=n.internals.isEqual;i.prototype.equals=function(t){return t===this?!0:null==t?!1:"N"!==t.kind?!1:this.predicate(t.value)},o.prototype.equals=function(t){return t===this?!0:null==t?!1:"E"!==t.kind?!1:this.predicate(t.exception)};var m=n.ReactiveTest={created:100,subscribed:200,disposed:1e3,onNext:function(t,e){return"function"==typeof e?new y(t,new i(e)):new y(t,c.createOnNext(e))},onError:function(t,e){return"function"==typeof e?new y(t,new o(e)):new y(t,c.createOnError(e))},onCompleted:function(t){return new y(t,c.createOnCompleted())},subscribe:function(t,e){return new w(t,e)}},y=n.Recorded=function(t,e,n){this.time=t,this.value=e,this.comparer=n||v};y.prototype.equals=function(t){return this.time===t.time&&this.comparer(this.value,t.value)},y.prototype.toString=function(){return""+this.value+"@"+this.time};var w=n.Subscription=function(t,e){this.subscribe=t,this.unsubscribe=e||Number.MAX_VALUE};w.prototype.equals=function(t){return this.subscribe===t.subscribe&&this.unsubscribe===t.unsubscribe},w.prototype.toString=function(){return"("+this.subscribe+", "+this.unsubscribe===Number.MAX_VALUE?"Infinite":this.unsubscribe+")"};var g=n.MockDisposable=function(t){this.scheduler=t,this.disposes=[],this.disposes.push(this.scheduler.clock)};g.prototype.dispose=function(){this.disposes.push(this.scheduler.clock)};var E=function(t){function e(e){t.call(this),this.scheduler=e,this.messages=[]}b(e,t);var n=e.prototype;return n.onNext=function(t){this.messages.push(new y(this.scheduler.clock,c.createOnNext(t)))},n.onError=function(t){this.messages.push(new y(this.scheduler.clock,c.createOnError(t)))},n.onCompleted=function(){this.messages.push(new y(this.scheduler.clock,c.createOnCompleted()))},e}(s),x=function(t){function e(t){var e=this;this.observers.push(t),this.subscriptions.push(new w(this.scheduler.clock));var n=this.subscriptions.length-1;return f(function(){var r=e.observers.indexOf(t);e.observers.splice(r,1),e.subscriptions[n]=new w(e.subscriptions[n].subscribe,e.scheduler.clock)})}function n(n,r){t.call(this,e);var i,o,s=this;this.scheduler=n,this.messages=r,this.subscriptions=[],this.observers=[];for(var u=0,c=this.messages.length;c>u;u++)i=this.messages[u],o=i.value,function(t){n.scheduleAbsoluteWithState(null,i.time,function(){for(var e=s.observers.slice(0),n=0,r=e.length;r>n;n++)t.accept(e[n]);return l})}(o)}return b(n,t),n}(u),C=function(t){function e(t){var e,n,r=this;this.subscriptions.push(new w(this.scheduler.clock));for(var i=this.subscriptions.length-1,o=new p,s=0,u=this.messages.length;u>s;s++)e=this.messages[s],n=e.value,function(n){o.add(r.scheduler.scheduleRelativeWithState(null,e.time,function(){return n.accept(t),l}))}(n);return f(function(){r.subscriptions[i]=new w(r.subscriptions[i].subscribe,r.scheduler.clock),o.dispose()})}function n(n,r){t.call(this,e),this.scheduler=n,this.messages=r,this.subscriptions=[]}return b(n,t),n}(u);return n.TestScheduler=function(t){function e(t,e){return t>e?1:e>t?-1:0}function n(){t.call(this,0,e)}return b(n,t),n.prototype.scheduleAbsoluteWithState=function(e,n,r){return this.clock>=n&&(n=this.clock+1),t.prototype.scheduleAbsoluteWithState.call(this,e,n,r)},n.prototype.add=function(t,e){return t+e},n.prototype.toDateTimeOffset=function(t){return new Date(t).getTime()},n.prototype.toRelative=function(t){return t},n.prototype.startWithTiming=function(t,e,n,r){var i,o,s=this.createObserver();return this.scheduleAbsoluteWithState(null,e,function(){return i=t(),l}),this.scheduleAbsoluteWithState(null,n,function(){return o=i.subscribe(s),l}),this.scheduleAbsoluteWithState(null,r,function(){return o.dispose(),l}),this.start(),s},n.prototype.startWithDispose=function(t,e){return this.startWithTiming(t,m.created,m.subscribed,e)},n.prototype.startWithCreate=function(t){return this.startWithTiming(t,m.created,m.subscribed,m.disposed)},n.prototype.createHotObservable=function(){var t=r(arguments,0);return new x(this,t)},n.prototype.createColdObservable=function(){var t=r(arguments,0);return new C(this,t)},n.prototype.createObserver=function(){return new E(this)},n}(a),n}); \ No newline at end of file diff --git a/ajax/libs/rxjs/2.2.28/rx.time.js b/ajax/libs/rxjs/2.2.28/rx.time.js new file mode 100644 index 000000000..868079ce8 --- /dev/null +++ b/ajax/libs/rxjs/2.2.28/rx.time.js @@ -0,0 +1,1166 @@ +// 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 (typeof define === 'function' && define.amd) { + define(['rx', 'exports'], function (Rx, exports) { + root.Rx = factory(root, exports, Rx); + return root.Rx; + }); + } 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.timeout, + SingleAssignmentDisposable = Rx.SingleAssignmentDisposable, + SerialDisposable = Rx.SerialDisposable, + CompositeDisposable = Rx.CompositeDisposable, + RefCountDisposable = Rx.RefCountDisposable, + Subject = Rx.Subject, + addRef = Rx.internals.addRef, + normalizeTime = Rx.Scheduler.normalize, + isPromise = Rx.helpers.isPromise, + observableFromPromise = Observable.fromPromise; + + function observableTimerDate(dueTime, scheduler) { + return new AnonymousObservable(function (observer) { + return scheduler.scheduleWithAbsolute(dueTime, function () { + observer.onNext(0); + observer.onCompleted(); + }); + }); + } + + function observableTimerDateAndPeriod(dueTime, period, scheduler) { + var p = normalizeTime(period); + return new AnonymousObservable(function (observer) { + var count = 0, d = dueTime; + return scheduler.scheduleRecursiveWithAbsolute(d, function (self) { + var now; + if (p > 0) { + now = scheduler.now(); + d = d + p; + if (d <= now) { + d = now + p; + } + } + observer.onNext(count++); + self(d); + }); + }); + } + + function observableTimerTimeSpan(dueTime, scheduler) { + var d = normalizeTime(dueTime); + return new AnonymousObservable(function (observer) { + return scheduler.scheduleWithRelative(d, function () { + observer.onNext(0); + observer.onCompleted(); + }); + }); + } + + function observableTimerTimeSpanAndPeriod(dueTime, period, scheduler) { + if (dueTime === period) { + return new AnonymousObservable(function (observer) { + return scheduler.schedulePeriodicWithState(0, period, function (count) { + observer.onNext(count); + return count + 1; + }); + }); + } + return 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) { + scheduler || (scheduler = timeoutScheduler); + return observableTimerTimeSpanAndPeriod(period, period, scheduler); + }; + + /** + * Returns an observable sequence that produces a value after dueTime has elapsed and then after each period. + * + * @example + * 1 - res = Rx.Observable.timer(new Date()); + * 2 - res = Rx.Observable.timer(new Date(), 1000); + * 3 - res = Rx.Observable.timer(new Date(), Rx.Scheduler.timeout); + * 4 - res = Rx.Observable.timer(new Date(), 1000, Rx.Scheduler.timeout); + * + * 5 - res = Rx.Observable.timer(5000); + * 6 - res = Rx.Observable.timer(5000, 1000); + * 7 - res = Rx.Observable.timer(5000, Rx.Scheduler.timeout); + * 8 - res = Rx.Observable.timer(5000, 1000, Rx.Scheduler.timeout); + * + * @param {Number} dueTime Absolute (specified as a Date object) or relative time (specified as an integer denoting milliseconds) at which to produce the first value. + * @param {Mixed} [periodOrScheduler] Period to produce subsequent values (specified as an integer denoting milliseconds), or the scheduler to run the timer on. If not specified, the resulting timer is not recurring. + * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, the timeout scheduler is used. + * @returns {Observable} An observable sequence that produces a value after due time has elapsed and then each period. + */ + var observableTimer = Observable.timer = function (dueTime, periodOrScheduler, scheduler) { + var period; + scheduler || (scheduler = timeoutScheduler); + if (periodOrScheduler !== undefined && typeof periodOrScheduler === 'number') { + period = periodOrScheduler; + } else if (periodOrScheduler !== undefined && typeof periodOrScheduler === 'object') { + scheduler = periodOrScheduler; + } + if (dueTime instanceof Date && period === undefined) { + return observableTimerDate(dueTime.getTime(), scheduler); + } + if (dueTime instanceof Date && period !== undefined) { + period = periodOrScheduler; + return observableTimerDateAndPeriod(dueTime.getTime(), period, scheduler); + } + if (period === undefined) { + return observableTimerTimeSpan(dueTime, scheduler); + } + return observableTimerTimeSpanAndPeriod(dueTime, period, scheduler); + }; + + function observableDelayTimeSpan(dueTime, scheduler) { + var source = this; + return new AnonymousObservable(function (observer) { + var active = false, + cancelable = new SerialDisposable(), + exception = null, + q = [], + running = false, + subscription; + subscription = source.materialize().timestamp(scheduler).subscribe(function (notification) { + var d, shouldRun; + if (notification.value.kind === 'E') { + q = []; + q.push(notification); + exception = notification.value.exception; + shouldRun = !running; + } else { + q.push({ value: notification.value, timestamp: notification.timestamp + dueTime }); + shouldRun = !active; + active = true; + } + if (shouldRun) { + if (exception !== null) { + observer.onError(exception); + } else { + d = new SingleAssignmentDisposable(); + cancelable.setDisposable(d); + d.setDisposable(scheduler.scheduleRecursiveWithRelative(dueTime, function (self) { + var e, recurseDueTime, result, shouldRecurse; + if (exception !== null) { + return; + } + running = true; + do { + result = null; + if (q.length > 0 && q[0].timestamp - scheduler.now() <= 0) { + result = q.shift().value; + } + if (result !== null) { + result.accept(observer); + } + } while (result !== null); + shouldRecurse = false; + recurseDueTime = 0; + if (q.length > 0) { + shouldRecurse = true; + recurseDueTime = Math.max(0, q[0].timestamp - scheduler.now()); + } else { + active = false; + } + e = exception; + running = false; + if (e !== null) { + observer.onError(e); + } else if (shouldRecurse) { + self(recurseDueTime); + } + })); + } + } + }); + return new CompositeDisposable(subscription, cancelable); + }); + } + + function observableDelayDate(dueTime, scheduler) { + var self = this; + return observableDefer(function () { + var timeSpan = dueTime - scheduler.now(); + return observableDelayTimeSpan.call(self, timeSpan, 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) { + scheduler || (scheduler = timeoutScheduler); + return dueTime instanceof Date ? + observableDelayDate.call(this, dueTime.getTime(), scheduler) : + observableDelayTimeSpan.call(this, dueTime, scheduler); + }; + + /** + * Ignores values from an observable sequence which are followed by another value before dueTime. + * + * @example + * 1 - res = source.throttle(5000); // 5 seconds + * 2 - res = source.throttle(5000, scheduler); + * + * @param {Number} dueTime Duration of the throttle period for each value (specified as an integer denoting milliseconds). + * @param {Scheduler} [scheduler] Scheduler to run the throttle timers on. If not specified, the timeout scheduler is used. + * @returns {Observable} The throttled sequence. + */ + observableProto.throttle = function (dueTime, scheduler) { + scheduler || (scheduler = timeoutScheduler); + var source = this; + return this.throttleWithSelector(function () { return observableTimer(dueTime, scheduler); }) + }; + + /** + * Projects each element of an observable sequence into zero or more windows which are produced based on timing information. + * + * @example + * 1 - res = xs.windowWithTime(1000, scheduler); // non-overlapping segments of 1 second + * 2 - res = xs.windowWithTime(1000, 500 , scheduler); // segments of 1 second with time shift 0.5 seconds + * + * @param {Number} timeSpan Length of each window (specified as an integer denoting milliseconds). + * @param {Mixed} [timeShiftOrScheduler] Interval between creation of consecutive windows (specified as an integer denoting milliseconds), or an optional scheduler parameter. If not specified, the time shift corresponds to the timeSpan parameter, resulting in non-overlapping adjacent windows. + * @param {Scheduler} [scheduler] Scheduler to run windowing timers on. If not specified, the timeout scheduler is used. + * @returns {Observable} An observable sequence of windows. + */ + observableProto.windowWithTime = function (timeSpan, timeShiftOrScheduler, scheduler) { + var source = this, timeShift; + if (timeShiftOrScheduler === undefined) { + timeShift = timeSpan; + } + if (scheduler === undefined) { + scheduler = timeoutScheduler; + } + if (typeof timeShiftOrScheduler === 'number') { + timeShift = timeShiftOrScheduler; + } else if (typeof timeShiftOrScheduler === 'object') { + timeShift = timeSpan; + scheduler = timeShiftOrScheduler; + } + return new AnonymousObservable(function (observer) { + var groupDisposable, + nextShift = timeShift, + nextSpan = timeSpan, + q = [], + refCountDisposable, + timerD = new SerialDisposable(), + totalTime = 0; + groupDisposable = new CompositeDisposable(timerD), + refCountDisposable = new RefCountDisposable(groupDisposable); + + 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 () { + var s; + if (isShift) { + s = new Subject(); + q.push(s); + observer.onNext(addRef(s, refCountDisposable)); + } + if (isSpan) { + s = q.shift(); + s.onCompleted(); + } + createTimer(); + })); + }; + q.push(new Subject()); + observer.onNext(addRef(q[0], refCountDisposable)); + createTimer(); + groupDisposable.add(source.subscribe(function (x) { + var i, s; + for (i = 0; i < q.length; i++) { + s = q[i]; + s.onNext(x); + } + }, function (e) { + var i, s; + for (i = 0; i < q.length; i++) { + s = q[i]; + s.onError(e); + } + observer.onError(e); + }, function () { + var i, s; + for (i = 0; i < q.length; i++) { + s = q[i]; + s.onCompleted(); + } + observer.onCompleted(); + })); + return refCountDisposable; + }); + }; + + /** + * Projects each element of an observable sequence into a window that is completed when either it's full or a given amount of time has elapsed. + * @example + * 1 - res = source.windowWithTimeOrCount(5000, 50); // 5s or 50 items + * 2 - res = source.windowWithTimeOrCount(5000, 50, scheduler); //5s or 50 items + * + * @memberOf Observable# + * @param {Number} timeSpan Maximum time length of a window. + * @param {Number} count Maximum element count of a window. + * @param {Scheduler} [scheduler] Scheduler to run windowing timers on. If not specified, the timeout scheduler is used. + * @returns {Observable} An observable sequence of windows. + */ + observableProto.windowWithTimeOrCount = function (timeSpan, count, scheduler) { + var source = this; + scheduler || (scheduler = timeoutScheduler); + return new AnonymousObservable(function (observer) { + var createTimer, + groupDisposable, + n = 0, + refCountDisposable, + s, + timerD = new SerialDisposable(), + windowId = 0; + groupDisposable = new CompositeDisposable(timerD); + refCountDisposable = new RefCountDisposable(groupDisposable); + createTimer = function (id) { + var m = new SingleAssignmentDisposable(); + timerD.setDisposable(m); + m.setDisposable(scheduler.scheduleWithRelative(timeSpan, function () { + var newId; + if (id !== windowId) { + return; + } + n = 0; + newId = ++windowId; + s.onCompleted(); + s = new Subject(); + observer.onNext(addRef(s, refCountDisposable)); + createTimer(newId); + })); + }; + s = new Subject(); + observer.onNext(addRef(s, refCountDisposable)); + createTimer(0); + groupDisposable.add(source.subscribe(function (x) { + var newId = 0, newWindow = false; + s.onNext(x); + n++; + if (n === count) { + newWindow = true; + n = 0; + newId = ++windowId; + s.onCompleted(); + s = new Subject(); + observer.onNext(addRef(s, refCountDisposable)); + } + if (newWindow) { + createTimer(newId); + } + }, function (e) { + s.onError(e); + observer.onError(e); + }, function () { + s.onCompleted(); + observer.onCompleted(); + })); + return refCountDisposable; + }); + }; + + /** + * 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; + scheduler || (scheduler = timeoutScheduler); + return observableDefer(function () { + var last = scheduler.now(); + return source.select(function (x) { + var now = scheduler.now(), span = now - last; + last = now; + return { + value: x, + interval: span + }; + }); + }); + }; + + /** + * Records the timestamp for each value in an observable sequence. + * + * @example + * 1 - res = source.timestamp(); // produces { value: x, timestamp: ts } + * 2 - res = source.timestamp(Rx.Scheduler.timeout); + * + * @param {Scheduler} [scheduler] Scheduler used to compute timestamps. If not specified, the timeout scheduler is used. + * @returns {Observable} An observable sequence with timestamp information on values. + */ + observableProto.timestamp = function (scheduler) { + scheduler || (scheduler = timeoutScheduler); + return this.select(function (x) { + return { + value: x, + timestamp: scheduler.now() + }; + }); + }; + + function sampleObservable(source, sampler) { + + return new AnonymousObservable(function (observer) { + var atEnd, value, hasValue; + + function sampleSubscribe() { + if (hasValue) { + hasValue = false; + observer.onNext(value); + } + if (atEnd) { + observer.onCompleted(); + } + } + + return new CompositeDisposable( + source.subscribe(function (newValue) { + hasValue = true; + value = newValue; + }, observer.onError.bind(observer), function () { + atEnd = true; + }), + sampler.subscribe(sampleSubscribe, observer.onError.bind(observer), sampleSubscribe) + ); + }); + } + + /** + * Samples the observable sequence at each interval. + * + * @example + * 1 - res = source.sample(sampleObservable); // Sampler tick sequence + * 2 - res = source.sample(5000); // 5 seconds + * 2 - res = source.sample(5000, Rx.Scheduler.timeout); // 5 seconds + * + * @param {Mixed} intervalOrSampler Interval at which to sample (specified as an integer denoting milliseconds) or Sampler Observable. + * @param {Scheduler} [scheduler] Scheduler to run the sampling timer on. If not specified, the timeout scheduler is used. + * @returns {Observable} Sampled observable sequence. + */ + observableProto.sample = function (intervalOrSampler, scheduler) { + scheduler || (scheduler = timeoutScheduler); + if (typeof intervalOrSampler === 'number') { + return sampleObservable(this, observableinterval(intervalOrSampler, scheduler)); + } + return sampleObservable(this, intervalOrSampler); + }; + + /** + * Returns the source observable sequence or the other observable sequence if dueTime elapses. + * + * @example + * 1 - res = source.timeout(new Date()); // As a date + * 2 - res = source.timeout(5000); // 5 seconds + * 3 - res = source.timeout(new Date(), Rx.Observable.returnValue(42)); // As a date and timeout observable + * 4 - res = source.timeout(5000, Rx.Observable.returnValue(42)); // 5 seconds and timeout observable + * 5 - res = source.timeout(new Date(), Rx.Observable.returnValue(42), Rx.Scheduler.timeout); // As a date and timeout observable + * 6 - res = source.timeout(5000, Rx.Observable.returnValue(42), Rx.Scheduler.timeout); // 5 seconds and timeout observable + * + * @param {Number} dueTime Absolute (specified as a Date object) or relative time (specified as an integer denoting milliseconds) when a timeout occurs. + * @param {Observable} [other] Sequence to return in case of a timeout. If not specified, a timeout error throwing sequence will be used. + * @param {Scheduler} [scheduler] Scheduler to run the timeout timers on. If not specified, the timeout scheduler is used. + * @returns {Observable} The source sequence switching to the other sequence in case of a timeout. + */ + observableProto.timeout = function (dueTime, other, scheduler) { + other || (other = observableThrow(new Error('Timeout'))); + scheduler || (scheduler = timeoutScheduler); + + var source = this, schedulerMethod = dueTime instanceof Date ? + 'scheduleWithAbsolute' : + 'scheduleWithRelative'; + + return new AnonymousObservable(function (observer) { + var id = 0, + original = new SingleAssignmentDisposable(), + subscription = new SerialDisposable(), + switched = false, + timer = new SerialDisposable(); + + subscription.setDisposable(original); + + var createTimer = function () { + var myId = id; + timer.setDisposable(scheduler[schedulerMethod](dueTime, function () { + if (id === myId) { + isPromise(other) && (other = observableFromPromise(other)); + subscription.setDisposable(other.subscribe(observer)); + } + })); + }; + + createTimer(); + + original.setDisposable(source.subscribe(function (x) { + if (!switched) { + id++; + observer.onNext(x); + createTimer(); + } + }, function (e) { + if (!switched) { + id++; + observer.onError(e); + } + }, function () { + if (!switched) { + id++; + observer.onCompleted(); + } + })); + return new CompositeDisposable(subscription, timer); + }); + }; + + /** + * Generates an observable sequence by iterating a state from an initial state until the condition fails. + * + * @example + * res = source.generateWithAbsoluteTime(0, + * function (x) { return return true; }, + * function (x) { return x + 1; }, + * function (x) { return x; }, + * function (x) { return new Date(); } + * }); + * + * @param {Mixed} initialState Initial state. + * @param {Function} condition Condition to terminate generation (upon returning false). + * @param {Function} iterate Iteration step function. + * @param {Function} resultSelector Selector function for results produced in the sequence. + * @param {Function} timeSelector Time selector function to control the speed of values being produced each iteration, returning Date values. + * @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not specified, the timeout scheduler is used. + * @returns {Observable} The generated sequence. + */ + Observable.generateWithAbsoluteTime = function (initialState, condition, iterate, resultSelector, timeSelector, scheduler) { + scheduler || (scheduler = timeoutScheduler); + return new AnonymousObservable(function (observer) { + var first = true, + hasResult = false, + result, + state = initialState, + time; + return scheduler.scheduleRecursiveWithAbsolute(scheduler.now(), function (self) { + if (hasResult) { + observer.onNext(result); + } + try { + if (first) { + first = false; + } else { + state = iterate(state); + } + hasResult = condition(state); + if (hasResult) { + result = resultSelector(state); + time = timeSelector(state); + } + } catch (e) { + observer.onError(e); + return; + } + if (hasResult) { + self(time); + } else { + observer.onCompleted(); + } + }); + }); + }; + + /** + * Generates an observable sequence by iterating a state from an initial state until the condition fails. + * + * @example + * res = source.generateWithRelativeTime(0, + * function (x) { return return true; }, + * function (x) { return x + 1; }, + * function (x) { return x; }, + * function (x) { return 500; } + * ); + * + * @param {Mixed} initialState Initial state. + * @param {Function} condition Condition to terminate generation (upon returning false). + * @param {Function} iterate Iteration step function. + * @param {Function} resultSelector Selector function for results produced in the sequence. + * @param {Function} timeSelector Time selector function to control the speed of values being produced each iteration, returning integer values denoting milliseconds. + * @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not specified, the timeout scheduler is used. + * @returns {Observable} The generated sequence. + */ + Observable.generateWithRelativeTime = function (initialState, condition, iterate, resultSelector, timeSelector, scheduler) { + scheduler || (scheduler = timeoutScheduler); + return new AnonymousObservable(function (observer) { + var first = true, + hasResult = false, + result, + state = initialState, + time; + return scheduler.scheduleRecursiveWithRelative(0, function (self) { + if (hasResult) { + observer.onNext(result); + } + try { + if (first) { + first = false; + } else { + state = iterate(state); + } + hasResult = condition(state); + if (hasResult) { + result = resultSelector(state); + time = timeSelector(state); + } + } catch (e) { + observer.onError(e); + return; + } + if (hasResult) { + self(time); + } else { + observer.onCompleted(); + } + }); + }); + }; + + /** + * Time shifts the observable sequence by delaying the subscription. + * + * @example + * 1 - res = source.delaySubscription(5000); // 5s + * 2 - res = source.delaySubscription(5000, Rx.Scheduler.timeout); // 5 seconds + * + * @param {Number} dueTime Absolute or relative time to perform the subscription at. + * @param {Scheduler} [scheduler] Scheduler to run the subscription delay timer on. If not specified, the timeout scheduler is used. + * @returns {Observable} Time-shifted sequence. + */ + observableProto.delaySubscription = function (dueTime, scheduler) { + scheduler || (scheduler = timeoutScheduler); + return this.delayWithSelector(observableTimer(dueTime, scheduler), function () { return observableEmpty(); }); + }; + + /** + * Time shifts the observable sequence based on a subscription delay and a delay selector function for each element. + * + * @example + * 1 - res = source.delayWithSelector(function (x) { return Rx.Scheduler.timer(5000); }); // with selector only + * 1 - res = source.delayWithSelector(Rx.Observable.timer(2000), function (x) { return Rx.Observable.timer(x); }); // with delay and selector + * + * @param {Observable} [subscriptionDelay] Sequence indicating the delay for the subscription to the source. + * @param {Function} delayDurationSelector Selector function to retrieve a sequence indicating the delay for each given element. + * @returns {Observable} Time-shifted sequence. + */ + observableProto.delayWithSelector = function (subscriptionDelay, delayDurationSelector) { + var source = this, subDelay, selector; + if (typeof subscriptionDelay === 'function') { + selector = subscriptionDelay; + } else { + subDelay = subscriptionDelay; + selector = delayDurationSelector; + } + return new AnonymousObservable(function (observer) { + var delays = new CompositeDisposable(), atEnd = false, done = function () { + if (atEnd && delays.length === 0) { + observer.onCompleted(); + } + }, subscription = new SerialDisposable(), start = function () { + subscription.setDisposable(source.subscribe(function (x) { + var delay; + try { + delay = selector(x); + } catch (error) { + observer.onError(error); + return; + } + var d = new SingleAssignmentDisposable(); + delays.add(d); + d.setDisposable(delay.subscribe(function () { + observer.onNext(x); + delays.remove(d); + done(); + }, observer.onError.bind(observer), function () { + observer.onNext(x); + delays.remove(d); + done(); + })); + }, observer.onError.bind(observer), function () { + atEnd = true; + subscription.dispose(); + done(); + })); + }; + + if (!subDelay) { + start(); + } else { + subscription.setDisposable(subDelay.subscribe(function () { + start(); + }, observer.onError.bind(observer), function () { start(); })); + } + + return new CompositeDisposable(subscription, delays); + }); + }; + + /** + * Returns the source observable sequence, switching to the other observable sequence if a timeout is signaled. + * + * @example + * 1 - res = source.timeoutWithSelector(Rx.Observable.timer(500)); + * 2 - res = source.timeoutWithSelector(Rx.Observable.timer(500), function (x) { return Rx.Observable.timer(200); }); + * 3 - res = source.timeoutWithSelector(Rx.Observable.timer(500), function (x) { return Rx.Observable.timer(200); }, Rx.Observable.returnValue(42)); + * + * @param {Observable} [firstTimeout] Observable sequence that represents the timeout for the first element. If not provided, this defaults to Observable.never(). + * @param {Function} [timeoutDurationSelector] Selector to retrieve an observable sequence that represents the timeout between the current element and the next element. + * @param {Observable} [other] Sequence to return in case of a timeout. If not provided, this is set to Observable.throwException(). + * @returns {Observable} The source sequence switching to the other sequence in case of a timeout. + */ + observableProto.timeoutWithSelector = function (firstTimeout, timeoutdurationSelector, other) { + if (arguments.length === 1) { + timeoutdurationSelector = firstTimeout; + var firstTimeout = observableNever(); + } + other || (other = observableThrow(new Error('Timeout'))); + var source = this; + return new AnonymousObservable(function (observer) { + var subscription = new SerialDisposable(), timer = new SerialDisposable(), original = new SingleAssignmentDisposable(); + + subscription.setDisposable(original); + + var id = 0, switched = false, setTimer = function (timeout) { + var myId = id, timerWins = function () { + return id === myId; + }; + var d = new SingleAssignmentDisposable(); + timer.setDisposable(d); + d.setDisposable(timeout.subscribe(function () { + if (timerWins()) { + subscription.setDisposable(other.subscribe(observer)); + } + d.dispose(); + }, function (e) { + if (timerWins()) { + observer.onError(e); + } + }, function () { + if (timerWins()) { + subscription.setDisposable(other.subscribe(observer)); + } + })); + }; + + setTimer(firstTimeout); + var observerWins = function () { + var res = !switched; + if (res) { + id++; + } + return res; + }; + + original.setDisposable(source.subscribe(function (x) { + if (observerWins()) { + observer.onNext(x); + var timeout; + try { + timeout = timeoutdurationSelector(x); + } catch (e) { + observer.onError(e); + return; + } + setTimer(timeout); + } + }, function (e) { + if (observerWins()) { + observer.onError(e); + } + }, function () { + if (observerWins()) { + observer.onCompleted(); + } + })); + return new CompositeDisposable(subscription, timer); + }); + }; + + /** + * Ignores values from an observable sequence which are followed by another value within a computed throttle duration. + * + * @example + * 1 - res = source.delayWithSelector(function (x) { return Rx.Scheduler.timer(x + x); }); + * + * @param {Function} throttleDurationSelector Selector function to retrieve a sequence indicating the throttle duration for each given element. + * @returns {Observable} The throttled sequence. + */ + observableProto.throttleWithSelector = function (throttleDurationSelector) { + var source = this; + return new AnonymousObservable(function (observer) { + var value, hasValue = false, cancelable = new SerialDisposable(), id = 0, subscription = source.subscribe(function (x) { + var throttle; + try { + throttle = throttleDurationSelector(x); + } catch (e) { + observer.onError(e); + return; + } + hasValue = true; + value = x; + id++; + var currentid = id, d = new SingleAssignmentDisposable(); + cancelable.setDisposable(d); + d.setDisposable(throttle.subscribe(function () { + if (hasValue && id === currentid) { + observer.onNext(value); + } + hasValue = false; + d.dispose(); + }, observer.onError.bind(observer), function () { + if (hasValue && id === currentid) { + observer.onNext(value); + } + hasValue = false; + d.dispose(); + })); + }, function (e) { + cancelable.dispose(); + observer.onError(e); + hasValue = false; + id++; + }, function () { + cancelable.dispose(); + if (hasValue) { + observer.onNext(value); + } + observer.onCompleted(); + hasValue = false; + id++; + }); + return new CompositeDisposable(subscription, cancelable); + }); + }; + + /** + * Skips elements for the specified duration from the end of the observable source sequence, using the specified scheduler to run timers. + * + * 1 - res = source.skipLastWithTime(5000); + * 2 - res = source.skipLastWithTime(5000, scheduler); + * + * @description + * This operator accumulates a queue with a length enough to store elements received during the initial duration window. + * As more elements are received, elements older than the specified duration are taken from the queue and produced on the + * result sequence. This causes elements to be delayed with duration. + * @param {Number} duration Duration for skipping elements from the end of the sequence. + * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout + * @returns {Observable} An observable sequence with the elements skipped during the specified duration from the end of the source sequence. + */ + observableProto.skipLastWithTime = function (duration, scheduler) { + scheduler || (scheduler = timeoutScheduler); + var source = this; + return new AnonymousObservable(function (observer) { + var q = []; + return source.subscribe(function (x) { + var now = scheduler.now(); + q.push({ interval: now, value: x }); + while (q.length > 0 && now - q[0].interval >= duration) { + observer.onNext(q.shift().value); + } + }, observer.onError.bind(observer), function () { + var now = scheduler.now(); + while (q.length > 0 && now - q[0].interval >= duration) { + observer.onNext(q.shift().value); + } + observer.onCompleted(); + }); + }); + }; + + /** + * Returns elements within the specified duration from the end of the observable source sequence, using the specified schedulers to run timers and to drain the collected elements. + * + * @example + * 1 - res = source.takeLastWithTime(5000, [optional timer scheduler], [optional loop scheduler]); + * @description + * This operator accumulates a queue with a length enough to store elements received during the initial duration window. + * As more elements are received, elements older than the specified duration are taken from the queue and produced on the + * result sequence. This causes elements to be delayed with duration. + * @param {Number} duration Duration for taking elements from the end of the sequence. + * @param {Scheduler} [timerScheduler] Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. + * @param {Scheduler} [loopScheduler] Scheduler to drain the collected elements. If not specified, defaults to Rx.Scheduler.immediate. + * @returns {Observable} An observable sequence with the elements taken during the specified duration from the end of the source sequence. + */ + observableProto.takeLastWithTime = function (duration, timerScheduler, loopScheduler) { + return this.takeLastBufferWithTime(duration, timerScheduler).selectMany(function (xs) { return observableFromArray(xs, loopScheduler); }); + }; + + /** + * Returns an array with the elements within the specified duration from the end of the observable source sequence, using the specified scheduler to run timers. + * + * @example + * 1 - res = source.takeLastBufferWithTime(5000, [optional scheduler]); + * @description + * This operator accumulates a queue with a length enough to store elements received during the initial duration window. + * As more elements are received, elements older than the specified duration are taken from the queue and produced on the + * result sequence. This causes elements to be delayed with duration. + * @param {Number} duration Duration for taking elements from the end of the sequence. + * @param {Scheduler} scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. + * @returns {Observable} An observable sequence containing a single array with the elements taken during the specified duration from the end of the source sequence. + */ + observableProto.takeLastBufferWithTime = function (duration, scheduler) { + var source = this; + scheduler || (scheduler = timeoutScheduler); + return new AnonymousObservable(function (observer) { + var q = []; + + return source.subscribe(function (x) { + var now = scheduler.now(); + q.push({ interval: now, value: x }); + while (q.length > 0 && now - q[0].interval >= duration) { + q.shift(); + } + }, observer.onError.bind(observer), function () { + var now = scheduler.now(), res = []; + while (q.length > 0) { + var next = q.shift(); + if (now - next.interval <= duration) { + res.push(next.value); + } + } + + observer.onNext(res); + observer.onCompleted(); + }); + }); + }; + + /** + * Takes elements for the specified duration from the start of the observable source sequence, using the specified scheduler to run timers. + * + * @example + * 1 - res = source.takeWithTime(5000, [optional scheduler]); + * @description + * This operator accumulates a queue with a length enough to store elements received during the initial duration window. + * As more elements are received, elements older than the specified duration are taken from the queue and produced on the + * result sequence. This causes elements to be delayed with duration. + * @param {Number} duration Duration for taking elements from the start of the sequence. + * @param {Scheduler} scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. + * @returns {Observable} An observable sequence with the elements taken during the specified duration from the start of the source sequence. + */ + observableProto.takeWithTime = function (duration, scheduler) { + var source = this; + scheduler || (scheduler = timeoutScheduler); + return new AnonymousObservable(function (observer) { + var t = scheduler.scheduleWithRelative(duration, function () { + observer.onCompleted(); + }); + + return new CompositeDisposable(t, source.subscribe(observer)); + }); + }; + + /** + * Skips elements for the specified duration from the start of the observable source sequence, using the specified scheduler to run timers. + * + * @example + * 1 - res = source.skipWithTime(5000, [optional scheduler]); + * + * @description + * Specifying a zero value for duration doesn't guarantee no elements will be dropped from the start of the source sequence. + * This is a side-effect of the asynchrony introduced by the scheduler, where the action that causes callbacks from the source sequence to be forwarded + * may not execute immediately, despite the zero due time. + * + * Errors produced by the source sequence are always forwarded to the result sequence, even if the error occurs before the duration. + * @param {Number} duration Duration for skipping elements from the start of the sequence. + * @param {Scheduler} scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. + * @returns {Observable} An observable sequence with the elements skipped during the specified duration from the start of the source sequence. + */ + observableProto.skipWithTime = function (duration, scheduler) { + var source = this; + scheduler || (scheduler = timeoutScheduler); + return new AnonymousObservable(function (observer) { + var open = false, + t = scheduler.scheduleWithRelative(duration, function () { open = true; }), + d = source.subscribe(function (x) { + if (open) { + observer.onNext(x); + } + }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); + + return new CompositeDisposable(t, d); + }); + }; + + /** + * Skips elements from the observable source sequence until the specified start time, using the specified scheduler to run timers. + * Errors produced by the source sequence are always forwarded to the result sequence, even if the error occurs before the start time. + * + * @examples + * 1 - res = source.skipUntilWithTime(new Date(), [optional scheduler]); + * 2 - res = source.skipUntilWithTime(5000, [optional scheduler]); + * @param startTime Time to start taking elements from the source sequence. If this value is less than or equal to Date(), no elements will be skipped. + * @param scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. + * @returns {Observable} An observable sequence with the elements skipped until the specified start time. + */ + observableProto.skipUntilWithTime = function (startTime, scheduler) { + scheduler || (scheduler = timeoutScheduler); + var source = this, schedulerMethod = startTime instanceof Date ? + 'scheduleWithAbsolute' : + 'scheduleWithRelative'; + return new AnonymousObservable(function (observer) { + var open = false; + + return new CompositeDisposable( + scheduler[schedulerMethod](startTime, function () { open = true; }), + source.subscribe( + function (x) { open && observer.onNext(x); }, + observer.onError.bind(observer), + observer.onCompleted.bind(observer))); + }); + }; + + /** + * Takes elements for the specified duration until the specified end time, using the specified scheduler to run timers. + * + * @example + * 1 - res = source.takeUntilWithTime(new Date(), [optional scheduler]); + * 2 - res = source.takeUntilWithTime(5000, [optional scheduler]); + * @param {Number | Date} endTime Time to stop taking elements from the source sequence. If this value is less than or equal to new Date(), the result stream will complete immediately. + * @param {Scheduler} scheduler Scheduler to run the timer on. + * @returns {Observable} An observable sequence with the elements taken until the specified end time. + */ + observableProto.takeUntilWithTime = function (endTime, scheduler) { + scheduler || (scheduler = timeoutScheduler); + var source = this, schedulerMethod = endTime instanceof Date ? + 'scheduleWithAbsolute' : + 'scheduleWithRelative'; + return new AnonymousObservable(function (observer) { + return new CompositeDisposable(scheduler[schedulerMethod](endTime, function () { + observer.onCompleted(); + }), source.subscribe(observer)); + }); + }; + + return Rx; +})); \ No newline at end of file diff --git a/ajax/libs/rxjs/2.2.28/rx.time.min.js b/ajax/libs/rxjs/2.2.28/rx.time.min.js new file mode 100644 index 000000000..10144d7ad --- /dev/null +++ b/ajax/libs/rxjs/2.2.28/rx.time.min.js @@ -0,0 +1 @@ +(function(t){var e={"boolean":!1,"function":!0,object:!0,number:!1,string:!1,undefined:!1},n=e[typeof window]&&window||this,r=e[typeof exports]&&exports&&!exports.nodeType&&exports,i=e[typeof module]&&module&&!module.nodeType&&module,o=(i&&i.exports===r&&r,e[typeof global]&&global);!o||o.global!==o&&o.window!==o||(n=o),"function"==typeof define&&define.amd?define(["rx","exports"],function(e,r){return n.Rx=t(n,r,e),n.Rx}):"object"==typeof module&&module&&module.exports===r?module.exports=t(n,module.exports,require("./rx")):n.Rx=t(n,{},n.Rx)}).call(this,function(t,e,n,r){function i(t,e){return new p(function(n){return e.scheduleWithAbsolute(t,function(){n.onNext(0),n.onCompleted()})})}function o(t,e,n){var r=N(e);return new p(function(e){var i=0,o=t;return n.scheduleRecursiveWithAbsolute(o,function(t){var s;r>0&&(s=n.now(),o+=r,s>=o&&(o=s+r)),e.onNext(i++),t(o)})})}function s(t,e){var n=N(t);return new p(function(t){return e.scheduleWithRelative(n,function(){t.onNext(0),t.onCompleted()})})}function u(t,e,n){return t===e?new p(function(t){return n.schedulePeriodicWithState(0,e,function(e){return t.onNext(e),e+1})}):d(function(){return o(n.now()+t,e,n)})}function c(t,e){var n=this;return new p(function(r){var i,o=!1,s=new E,u=null,c=[],a=!1;return i=n.materialize().timestamp(e).subscribe(function(n){var i,h;"E"===n.value.kind?(c=[],c.push(n),u=n.value.exception,h=!a):(c.push({value:n.value,timestamp:n.timestamp+t}),h=!o,o=!0),h&&(null!==u?r.onError(u):(i=new g,s.setDisposable(i),i.setDisposable(e.scheduleRecursiveWithRelative(t,function(t){var n,i,s,h;if(null===u){a=!0;do s=null,c.length>0&&0>=c[0].timestamp-e.now()&&(s=c.shift().value),null!==s&&s.accept(r);while(null!==s);h=!1,i=0,c.length>0?(h=!0,i=Math.max(0,c[0].timestamp-e.now())):o=!1,n=u,a=!1,null!==n?r.onError(n):h&&t(i)}}))))}),new x(i,s)})}function a(t,e){var n=this;return d(function(){var r=t-e.now();return c.call(n,r,e)})}function h(t,e){return new p(function(n){function r(){s&&(s=!1,n.onNext(o)),i&&n.onCompleted()}var i,o,s;return new x(t.subscribe(function(t){s=!0,o=t},n.onError.bind(n),function(){i=!0}),e.subscribe(r,n.onError.bind(n),r))})}var l=n.Observable,f=l.prototype,p=n.AnonymousObservable,d=l.defer,b=l.empty,v=l.never,m=l.throwException,y=l.fromArray,w=n.Scheduler.timeout,g=n.SingleAssignmentDisposable,E=n.SerialDisposable,x=n.CompositeDisposable,C=n.RefCountDisposable,D=n.Subject,S=n.internals.addRef,N=n.Scheduler.normalize,A=n.helpers.isPromise,_=l.fromPromise,O=l.interval=function(t,e){return e||(e=w),u(t,t,e)},j=l.timer=function(t,e,n){var c;return n||(n=w),e!==r&&"number"==typeof e?c=e:e!==r&&"object"==typeof e&&(n=e),t instanceof Date&&c===r?i(t.getTime(),n):t instanceof Date&&c!==r?(c=e,o(t.getTime(),c,n)):c===r?s(t,n):u(t,c,n)};return f.delay=function(t,e){return e||(e=w),t instanceof Date?a.call(this,t.getTime(),e):c.call(this,t,e)},f.throttle=function(t,e){return e||(e=w),this.throttleWithSelector(function(){return j(t,e)})},f.windowWithTime=function(t,e,n){var i,o=this;return e===r&&(i=t),n===r&&(n=w),"number"==typeof e?i=e:"object"==typeof e&&(i=t,n=e),new p(function(e){function r(){var t=new g,o=!1,s=!1;l.setDisposable(t),a===c?(o=!0,s=!0):c>a?o=!0:s=!0;var p=o?a:c,d=p-f;f=p,o&&(a+=i),s&&(c+=i),t.setDisposable(n.scheduleWithRelative(d,function(){var t;s&&(t=new D,h.push(t),e.onNext(S(t,u))),o&&(t=h.shift(),t.onCompleted()),r()}))}var s,u,c=i,a=t,h=[],l=new E,f=0;return s=new x(l),u=new C(s),h.push(new D),e.onNext(S(h[0],u)),r(),s.add(o.subscribe(function(t){var e,n;for(e=0;h.length>e;e++)n=h[e],n.onNext(t)},function(t){var n,r;for(n=0;h.length>n;n++)r=h[n],r.onError(t);e.onError(t)},function(){var t,n;for(t=0;h.length>t;t++)n=h[t],n.onCompleted();e.onCompleted()})),u})},f.windowWithTimeOrCount=function(t,e,n){var r=this;return n||(n=w),new p(function(i){var o,s,u,c,a=0,h=new E,l=0;return s=new x(h),u=new C(s),o=function(e){var r=new g;h.setDisposable(r),r.setDisposable(n.scheduleWithRelative(t,function(){var t;e===l&&(a=0,t=++l,c.onCompleted(),c=new D,i.onNext(S(c,u)),o(t))}))},c=new D,i.onNext(S(c,u)),o(0),s.add(r.subscribe(function(t){var n=0,r=!1;c.onNext(t),a++,a===e&&(r=!0,a=0,n=++l,c.onCompleted(),c=new D,i.onNext(S(c,u))),r&&o(n)},function(t){c.onError(t),i.onError(t)},function(){c.onCompleted(),i.onCompleted()})),u})},f.bufferWithTime=function(){return this.windowWithTime.apply(this,arguments).selectMany(function(t){return t.toArray()})},f.bufferWithTimeOrCount=function(t,e,n){return this.windowWithTimeOrCount(t,e,n).selectMany(function(t){return t.toArray()})},f.timeInterval=function(t){var e=this;return t||(t=w),d(function(){var n=t.now();return e.select(function(e){var r=t.now(),i=r-n;return n=r,{value:e,interval:i}})})},f.timestamp=function(t){return t||(t=w),this.select(function(e){return{value:e,timestamp:t.now()}})},f.sample=function(t,e){return e||(e=w),"number"==typeof t?h(this,O(t,e)):h(this,t)},f.timeout=function(t,e,n){e||(e=m(Error("Timeout"))),n||(n=w);var r=this,i=t instanceof Date?"scheduleWithAbsolute":"scheduleWithRelative";return new p(function(o){var s=0,u=new g,c=new E,a=!1,h=new E;c.setDisposable(u);var l=function(){var r=s;h.setDisposable(n[i](t,function(){s===r&&(A(e)&&(e=_(e)),c.setDisposable(e.subscribe(o)))}))};return l(),u.setDisposable(r.subscribe(function(t){a||(s++,o.onNext(t),l())},function(t){a||(s++,o.onError(t))},function(){a||(s++,o.onCompleted())})),new x(c,h)})},l.generateWithAbsoluteTime=function(t,e,n,i,o,s){return s||(s=w),new p(function(u){var c,a,h=!0,l=!1,f=t;return s.scheduleRecursiveWithAbsolute(s.now(),function(t){l&&u.onNext(c);try{h?h=!1:f=n(f),l=e(f),l&&(c=i(f),a=o(f))}catch(s){return u.onError(s),r}l?t(a):u.onCompleted()})})},l.generateWithRelativeTime=function(t,e,n,i,o,s){return s||(s=w),new p(function(u){var c,a,h=!0,l=!1,f=t;return s.scheduleRecursiveWithRelative(0,function(t){l&&u.onNext(c);try{h?h=!1:f=n(f),l=e(f),l&&(c=i(f),a=o(f))}catch(s){return u.onError(s),r}l?t(a):u.onCompleted()})})},f.delaySubscription=function(t,e){return e||(e=w),this.delayWithSelector(j(t,e),function(){return b()})},f.delayWithSelector=function(t,e){var n,i,o=this;return"function"==typeof t?i=t:(n=t,i=e),new p(function(t){var e=new x,s=!1,u=function(){s&&0===e.length&&t.onCompleted()},c=new E,a=function(){c.setDisposable(o.subscribe(function(n){var o;try{o=i(n)}catch(s){return t.onError(s),r}var c=new g;e.add(c),c.setDisposable(o.subscribe(function(){t.onNext(n),e.remove(c),u()},t.onError.bind(t),function(){t.onNext(n),e.remove(c),u()}))},t.onError.bind(t),function(){s=!0,c.dispose(),u()}))};return n?c.setDisposable(n.subscribe(function(){a()},t.onError.bind(t),function(){a()})):a(),new x(c,e)})},f.timeoutWithSelector=function(t,e,n){if(1===arguments.length){e=t;var t=v()}n||(n=m(Error("Timeout")));var i=this;return new p(function(o){var s=new E,u=new E,c=new g;s.setDisposable(c);var a=0,h=!1,l=function(t){var e=a,r=function(){return a===e},i=new g;u.setDisposable(i),i.setDisposable(t.subscribe(function(){r()&&s.setDisposable(n.subscribe(o)),i.dispose()},function(t){r()&&o.onError(t)},function(){r()&&s.setDisposable(n.subscribe(o))}))};l(t);var f=function(){var t=!h;return t&&a++,t};return c.setDisposable(i.subscribe(function(t){if(f()){o.onNext(t);var n;try{n=e(t)}catch(i){return o.onError(i),r}l(n)}},function(t){f()&&o.onError(t)},function(){f()&&o.onCompleted()})),new x(s,u)})},f.throttleWithSelector=function(t){var e=this;return new p(function(n){var i,o=!1,s=new E,u=0,c=e.subscribe(function(e){var c;try{c=t(e)}catch(a){return n.onError(a),r}o=!0,i=e,u++;var h=u,l=new g;s.setDisposable(l),l.setDisposable(c.subscribe(function(){o&&u===h&&n.onNext(i),o=!1,l.dispose()},n.onError.bind(n),function(){o&&u===h&&n.onNext(i),o=!1,l.dispose()}))},function(t){s.dispose(),n.onError(t),o=!1,u++},function(){s.dispose(),o&&n.onNext(i),n.onCompleted(),o=!1,u++});return new x(c,s)})},f.skipLastWithTime=function(t,e){e||(e=w);var n=this;return new p(function(r){var i=[];return n.subscribe(function(n){var o=e.now();for(i.push({interval:o,value:n});i.length>0&&o-i[0].interval>=t;)r.onNext(i.shift().value)},r.onError.bind(r),function(){for(var n=e.now();i.length>0&&n-i[0].interval>=t;)r.onNext(i.shift().value);r.onCompleted()})})},f.takeLastWithTime=function(t,e,n){return this.takeLastBufferWithTime(t,e).selectMany(function(t){return y(t,n)})},f.takeLastBufferWithTime=function(t,e){var n=this;return e||(e=w),new p(function(r){var i=[];return n.subscribe(function(n){var r=e.now();for(i.push({interval:r,value:n});i.length>0&&r-i[0].interval>=t;)i.shift()},r.onError.bind(r),function(){for(var n=e.now(),o=[];i.length>0;){var s=i.shift();t>=n-s.interval&&o.push(s.value)}r.onNext(o),r.onCompleted()})})},f.takeWithTime=function(t,e){var n=this;return e||(e=w),new p(function(r){var i=e.scheduleWithRelative(t,function(){r.onCompleted()});return new x(i,n.subscribe(r))})},f.skipWithTime=function(t,e){var n=this;return e||(e=w),new p(function(r){var i=!1,o=e.scheduleWithRelative(t,function(){i=!0}),s=n.subscribe(function(t){i&&r.onNext(t)},r.onError.bind(r),r.onCompleted.bind(r));return new x(o,s)})},f.skipUntilWithTime=function(t,e){e||(e=w);var n=this,r=t instanceof Date?"scheduleWithAbsolute":"scheduleWithRelative";return new p(function(i){var o=!1;return new x(e[r](t,function(){o=!0}),n.subscribe(function(t){o&&i.onNext(t)},i.onError.bind(i),i.onCompleted.bind(i)))})},f.takeUntilWithTime=function(t,e){e||(e=w);var n=this,r=t instanceof Date?"scheduleWithAbsolute":"scheduleWithRelative";return new p(function(i){return new x(e[r](t,function(){i.onCompleted()}),n.subscribe(i))})},n}); \ No newline at end of file diff --git a/ajax/libs/rxjs/2.2.28/rx.virtualtime.js b/ajax/libs/rxjs/2.2.28/rx.virtualtime.js new file mode 100644 index 000000000..be9129fb9 --- /dev/null +++ b/ajax/libs/rxjs/2.2.28/rx.virtualtime.js @@ -0,0 +1,335 @@ +// 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 (typeof define === 'function' && define.amd) { + define(['rx', 'exports'], function (Rx, exports) { + root.Rx = factory(root, exports, Rx); + return root.Rx; + }); + } 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; + + /** Provides a set of extension methods for virtual time scheduling. */ + Rx.VirtualTimeScheduler = (function (_super) { + + function notImplemented() { + throw new Error('Not implemented'); + } + + function localNow() { + return this.toDateTimeOffset(this.clock); + } + + function scheduleNow(state, action) { + return this.scheduleAbsoluteWithState(state, this.clock, action); + } + + function scheduleRelative(state, dueTime, action) { + return this.scheduleRelativeWithState(state, this.toRelative(dueTime), action); + } + + function scheduleAbsolute(state, dueTime, action) { + return this.scheduleRelativeWithState(state, this.toRelative(dueTime - this.now()), action); + } + + function invokeAction(scheduler, action) { + action(); + return disposableEmpty; + } + + inherits(VirtualTimeScheduler, _super); + + /** + * Creates a new virtual time scheduler with the specified initial clock value and absolute time comparer. + * + * @constructor + * @param {Number} initialClock Initial value for the clock. + * @param {Function} comparer Comparer to determine causality of events based on absolute time. + */ + function VirtualTimeScheduler(initialClock, comparer) { + this.clock = initialClock; + this.comparer = comparer; + this.isEnabled = false; + this.queue = new PriorityQueue(1024); + _super.call(this, localNow, scheduleNow, scheduleRelative, scheduleAbsolute); + } + + var VirtualTimeSchedulerPrototype = VirtualTimeScheduler.prototype; + + /** + * Adds a relative time value to an absolute time value. + * @param {Number} absolute Absolute virtual time value. + * @param {Number} relative Relative virtual time value to add. + * @return {Number} Resulting absolute virtual time sum value. + */ + VirtualTimeSchedulerPrototype.add = notImplemented; + + /** + * Converts an absolute time to a number + * @param {Any} The absolute time. + * @returns {Number} The absolute time in ms + */ + VirtualTimeSchedulerPrototype.toDateTimeOffset = notImplemented; + + /** + * Converts the TimeSpan value to a relative virtual time value. + * @param {Number} timeSpan TimeSpan value to convert. + * @return {Number} Corresponding relative virtual time value. + */ + VirtualTimeSchedulerPrototype.toRelative = notImplemented; + + /** + * Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be emulated using recursive scheduling. + * @param {Mixed} state Initial state passed to the action upon the first iteration. + * @param {Number} period Period for running the work periodically. + * @param {Function} action Action to be executed, potentially updating the state. + * @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort). + */ + VirtualTimeSchedulerPrototype.schedulePeriodicWithState = function (state, period, action) { + var s = new SchedulePeriodicRecursive(this, state, period, action); + return s.start(); + }; + + /** + * Schedules an action to be executed after dueTime. + * @param {Mixed} state State passed to the action to be executed. + * @param {Number} dueTime Relative time after which to execute the action. + * @param {Function} action Action to be executed. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + VirtualTimeSchedulerPrototype.scheduleRelativeWithState = function (state, dueTime, action) { + var runAt = this.add(this.clock, dueTime); + return this.scheduleAbsoluteWithState(state, runAt, action); + }; + + /** + * Schedules an action to be executed at dueTime. + * @param {Number} dueTime Relative time after which to execute the action. + * @param {Function} action Action to be executed. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + VirtualTimeSchedulerPrototype.scheduleRelative = function (dueTime, action) { + return this.scheduleRelativeWithState(action, dueTime, invokeAction); + }; + + /** + * Starts the virtual time scheduler. + */ + VirtualTimeSchedulerPrototype.start = function () { + var next; + if (!this.isEnabled) { + this.isEnabled = true; + do { + next = this.getNext(); + if (next !== null) { + if (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 next; + var dueToClock = this.comparer(this.clock, time); + if (this.comparer(this.clock, time) > 0) { + throw new Error(argumentOutOfRange); + } + if (dueToClock === 0) { + return; + } + if (!this.isEnabled) { + this.isEnabled = true; + do { + next = this.getNext(); + if (next !== null && this.comparer(next.dueTime, time) <= 0) { + if (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); + var dueToClock = this.comparer(this.clock, dt); + if (dueToClock > 0) { + throw new Error(argumentOutOfRange); + } + if (dueToClock === 0) { + return; + } + this.advanceTo(dt); + }; + + /** + * Advances the scheduler's clock by the specified relative time. + * @param {Number} time Relative time to advance the scheduler's clock by. + */ + VirtualTimeSchedulerPrototype.sleep = function (time) { + var dt = this.add(this.clock, time); + + if (this.comparer(this.clock, dt) >= 0) { + throw new Error(argumentOutOfRange); + } + + this.clock = dt; + }; + + /** + * Gets the next scheduled item to be executed. + * @returns {ScheduledItem} The next scheduled item. + */ + VirtualTimeSchedulerPrototype.getNext = function () { + var next; + while (this.queue.length > 0) { + 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, + run = function (scheduler, state1) { + self.queue.remove(si); + return action(scheduler, state1); + }, + si = new ScheduledItem(self, state, run, dueTime, self.comparer); + self.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; + }; + + /** + * @private + */ + 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; +})); \ No newline at end of file diff --git a/ajax/libs/rxjs/2.2.28/rx.virtualtime.min.js b/ajax/libs/rxjs/2.2.28/rx.virtualtime.min.js new file mode 100644 index 000000000..26d00bd62 --- /dev/null +++ b/ajax/libs/rxjs/2.2.28/rx.virtualtime.min.js @@ -0,0 +1 @@ +(function(t){var e={"boolean":!1,"function":!0,object:!0,number:!1,string:!1,undefined:!1},n=e[typeof window]&&window||this,r=e[typeof exports]&&exports&&!exports.nodeType&&exports,i=e[typeof module]&&module&&!module.nodeType&&module,o=(i&&i.exports===r&&r,e[typeof global]&&global);!o||o.global!==o&&o.window!==o||(n=o),"function"==typeof define&&define.amd?define(["rx","exports"],function(e,r){return n.Rx=t(n,r,e),n.Rx}):"object"==typeof module&&module&&module.exports===r?module.exports=t(n,module.exports,require("./rx")):n.Rx=t(n,{},n.Rx)}).call(this,function(t,e,n){var r=n.Scheduler,i=n.internals.PriorityQueue,o=n.internals.ScheduledItem,s=n.internals.SchedulePeriodicRecursive,u=n.Disposable.empty,c=n.internals.inherits,a=n.helpers.defaultSubComparer;return n.VirtualTimeScheduler=function(t){function e(){throw Error("Not implemented")}function n(){return this.toDateTimeOffset(this.clock)}function r(t,e){return this.scheduleAbsoluteWithState(t,this.clock,e)}function a(t,e,n){return this.scheduleRelativeWithState(t,this.toRelative(e),n)}function h(t,e,n){return this.scheduleRelativeWithState(t,this.toRelative(e-this.now()),n)}function l(t,e){return e(),u}function f(e,o){this.clock=e,this.comparer=o,this.isEnabled=!1,this.queue=new i(1024),t.call(this,n,r,a,h)}c(f,t);var p=f.prototype;return p.add=e,p.toDateTimeOffset=e,p.toRelative=e,p.schedulePeriodicWithState=function(t,e,n){var r=new s(this,t,e,n);return r.start()},p.scheduleRelativeWithState=function(t,e,n){var r=this.add(this.clock,e);return this.scheduleAbsoluteWithState(t,r,n)},p.scheduleRelative=function(t,e){return this.scheduleRelativeWithState(e,t,l)},p.start=function(){var t;if(!this.isEnabled){this.isEnabled=!0;do t=this.getNext(),null!==t?(this.comparer(t.dueTime,this.clock)>0&&(this.clock=t.dueTime),t.invoke()):this.isEnabled=!1;while(this.isEnabled)}},p.stop=function(){this.isEnabled=!1},p.advanceTo=function(t){var e,n=this.comparer(this.clock,t);if(this.comparer(this.clock,t)>0)throw Error(argumentOutOfRange);if(0!==n&&!this.isEnabled){this.isEnabled=!0;do e=this.getNext(),null!==e&&0>=this.comparer(e.dueTime,t)?(this.comparer(e.dueTime,this.clock)>0&&(this.clock=e.dueTime),e.invoke()):this.isEnabled=!1;while(this.isEnabled);this.clock=t}},p.advanceBy=function(t){var e=this.add(this.clock,t),n=this.comparer(this.clock,e);if(n>0)throw Error(argumentOutOfRange);0!==n&&this.advanceTo(e)},p.sleep=function(t){var e=this.add(this.clock,t);if(this.comparer(this.clock,e)>=0)throw Error(argumentOutOfRange);this.clock=e},p.getNext=function(){for(var t;this.queue.length>0;){if(t=this.queue.peek(),!t.isCancelled())return t;this.queue.dequeue()}return null},p.scheduleAbsolute=function(t,e){return this.scheduleAbsoluteWithState(e,t,l)},p.scheduleAbsoluteWithState=function(t,e,n){var r=this,i=function(t,e){return r.queue.remove(s),n(t,e)},s=new o(r,t,i,e,r.comparer);return r.queue.enqueue(s),s.disposable},f}(r),n.HistoricalScheduler=function(t){function e(e,n){var r=null==e?0:e,i=n||a;t.call(this,r,i)}c(e,t);var n=e.prototype;return n.add=function(t,e){return t+e},n.toDateTimeOffset=function(t){return new Date(t).getTime()},n.toRelative=function(t){return t},e}(n.VirtualTimeScheduler),n}); \ No newline at end of file diff --git a/ajax/libs/rxjs/2.2.28/v2.2.28.tar.gz b/ajax/libs/rxjs/2.2.28/v2.2.28.tar.gz new file mode 100644 index 000000000..242a1b876 Binary files /dev/null and b/ajax/libs/rxjs/2.2.28/v2.2.28.tar.gz differ diff --git a/ajax/libs/rxjs/package.json b/ajax/libs/rxjs/package.json index 1a43b8c6e..465d6a70d 100644 --- a/ajax/libs/rxjs/package.json +++ b/ajax/libs/rxjs/package.json @@ -3,7 +3,7 @@ "filename": "rx.min.js", "title": "Reactive Extensions for JavaScript (RxJS)", "description": "Library for composing asynchronous and event-based operations in JavaScript", - "version": "2.2.27", + "version": "2.2.28", "homepage": "https://github.com/Reactive-Extensions/RxJS", "author": { "name": "Cloud Programmability Team",