From ba796af4fcd04186ef844e9666a86e9dd336ba42 Mon Sep 17 00:00:00 2001 From: Erwin Mombay Date: Mon, 24 Aug 2015 01:16:03 -0700 Subject: [PATCH] feature(background): refactor background file to use observables --- background.js | 80 +- dist/hint.js | 3362 ++++++++------- gulpfile.js | 1 + libs/rx.all.js | 10664 +++++++++++++++++++++++++++++++++++++++++++++++ manifest.json | 1 + 5 files changed, 12398 insertions(+), 1710 deletions(-) create mode 100644 libs/rx.all.js diff --git a/background.js b/background.js index ac49c0a..d8bb1fd 100644 --- a/background.js +++ b/background.js @@ -5,9 +5,19 @@ var inspectedTabs = {}; // tabId -> buffered data var data = {}; -function bufferOrForward(message, sender) { - var tabId = sender.tab.id, - devToolsPort = inspectedTabs[tabId]; +var runtimeMessage = createRxFrom(chrome.runtime.onMessage, messageSelector); +var runtimeConnect = createRxFrom(chrome.runtime.onConnect); +var tabsRemoved = createRxFrom(chrome.tabs.onRemoved); + +runtimeMessage.forEach(bufferOrForward); +runtimeConnect.forEach(onConnect); +tabsRemoved.forEach(onTabsRemoved); + +function bufferOrForward(event) { + var message = event.message; + var sender = event.sender; + var tabId = sender.tab.id; + var devToolsPort = inspectedTabs[tabId]; if (!data[tabId] || message === 'refresh') { resetState(tabId); @@ -94,39 +104,37 @@ function bufferData(tabId, message) { // TODO: Handle digest timings } -// context script –> background -chrome.runtime.onMessage.addListener(bufferOrForward); - -chrome.runtime.onConnect.addListener(function(devToolsPort) { - - devToolsPort.onMessage.addListener(registerInspectedTabId); - - function registerInspectedTabId(inspectedTabId) { - inspectedTabs[inspectedTabId] = devToolsPort; - - if (!data[inspectedTabId]) { - resetState(inspectedTabId); - } - devToolsPort.postMessage({ - event: 'hydrate', - data: data[inspectedTabId] - }); +function onConnect(devToolsPort) { + var devToolsMessage = createRxFrom(devToolsPort.onMessage); + devToolsMessage.forEach(registerInspectedTabId.bind(null, devToolsPort)); + return event; +} - devToolsPort.onDisconnect.addListener(function () { - delete inspectedTabs[inspectedTabId]; - }); +function registerInspectedTabId(devToolsPort, inspectedTabId) { + inspectedTabs[inspectedTabId] = devToolsPort; - //devToolsPort.onMessage.removeListener(registerInspectedTabId); + if (!data[inspectedTabId]) { + resetState(inspectedTabId); } + devToolsPort.postMessage({ + event: 'hydrate', + data: data[inspectedTabId] + }); -}); + var devToolsDisconnect = createRxFrom(devToolsPort.onDisconnect); + devToolsDisconnect.forEach(onDisconnect); + return event; +} -chrome.tabs.onRemoved.addListener(function (tabId) { +function onDisconnect(inspectedTabId) { + delete inspectedTabs[inspectedTabId]; +} + +function onTabsRemoved(tabId) { if (data[tabId]) { delete data[tabId]; } -}); - +} function showPageAction(tabId) { chrome.pageAction.show(tabId); @@ -135,3 +143,19 @@ function showPageAction(tabId) { title: 'Batarang Active' }); } + +function createRxFrom(target, selector) { + return Rx.Observable.fromEventPattern( + function(handler) { target.addListener(handler); }, + function(handler) { target.removeListener(handler); }, + selector + ); +} + +function messageSelector() { + return { + message: arguments[0], + sender: arguments[1], + sendResponse: arguments[2] + }; +} diff --git a/dist/hint.js b/dist/hint.js index db4f2ab..e5af94e 100755 --- a/dist/hint.js +++ b/dist/hint.js @@ -1,625 +1,172 @@ (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o -1) || + angular.hint.emit('general:404module', 'Module ' + name + ' could not be found', SEVERITY_WARNING); + }); +} + +function hintModuleName(name) { + return 'ngHint' + title(name); +} + +function title(str) { + return str[0].toUpperCase() + str.substr(1); +} + +var LEVELS = [ + 'error', + 'warning', + 'suggestion' +]; + +},{"./src/modules/controllers":23,"./src/modules/events":24,"./src/modules/hintEmitter":25,"./src/modules/modules":26,"./src/modules/scopes":27}],2:[function(require,module,exports){ +module.exports = function debounceOn (fn, timeout, hash) { + var timeouts = {}; + + timeout = typeof timeout === 'number' ? timeout : (hash = timeout, 100); + hash = typeof hash === 'function' ? hash : defaultHash; + + return function () { + var key = hash.apply(null, arguments); + var args = arguments; + if (typeof timeouts[key] === 'undefined') { + timeouts[key] = setTimeout(function () { + delete timeouts[key]; + fn.apply(null, args); + }, timeout); + } + return function cancel () { + if (timeouts[key]) { + clearTimeout(timeouts[key]); + delete timeouts[key]; + return true; + } + return false; + }; }; +}; + +function defaultHash () { + return Array.prototype.join.call(arguments, '::'); } -/** - * @ngdoc type - * @name angular.Module - * @module ng - * @description +},{}],3:[function(require,module,exports){ +/*! + * EventEmitter2 + * https://github.com/hij1nx/EventEmitter2 * - * Interface for configuring angular {@link angular.module modules}. + * Copyright (c) 2013 hij1nx + * Licensed under the MIT license. */ +;!function(undefined) { -function setupModuleLoader(window) { - - var $injectorMinErr = minErr('$injector'); - var ngMinErr = minErr('ng'); + var isArray = Array.isArray ? Array.isArray : function _isArray(obj) { + return Object.prototype.toString.call(obj) === "[object Array]"; + }; + var defaultMaxListeners = 10; - function ensure(obj, name, factory) { - return obj[name] || (obj[name] = factory()); + function init() { + this._events = {}; + if (this._conf) { + configure.call(this, this._conf); + } } - var angular = ensure(window, 'angular', Object); - - // We need to expose `angular.$$minErr` to modules such as `ngResource` that reference it during bootstrap - angular.$$minErr = angular.$$minErr || minErr; + function configure(conf) { + if (conf) { - return ensure(angular, 'module', function() { - /** @type {Object.} */ - var modules = {}; - - /** - * @ngdoc function - * @name angular.module - * @module ng - * @description - * - * The `angular.module` is a global place for creating, registering and retrieving Angular - * modules. - * All modules (angular core or 3rd party) that should be available to an application must be - * registered using this mechanism. - * - * When passed two or more arguments, a new module is created. If passed only one argument, an - * existing module (the name passed as the first argument to `module`) is retrieved. - * - * - * # Module - * - * A module is a collection of services, directives, controllers, filters, and configuration information. - * `angular.module` is used to configure the {@link auto.$injector $injector}. - * - * ```js - * // Create a new module - * var myModule = angular.module('myModule', []); - * - * // register a new service - * myModule.value('appName', 'MyCoolApp'); - * - * // configure existing services inside initialization blocks. - * myModule.config(['$locationProvider', function($locationProvider) { - * // Configure existing providers - * $locationProvider.hashPrefix('!'); - * }]); - * ``` - * - * Then you can create an injector and load your modules like this: - * - * ```js - * var injector = angular.injector(['ng', 'myModule']) - * ``` - * - * However it's more likely that you'll just use - * {@link ng.directive:ngApp ngApp} or - * {@link angular.bootstrap} to simplify this process for you. - * - * @param {!string} name The name of the module to create or retrieve. - * @param {!Array.=} requires If specified then new module is being created. If - * unspecified then the module is being retrieved for further configuration. - * @param {Function=} configFn Optional configuration function for the module. Same as - * {@link angular.Module#config Module#config()}. - * @returns {module} new module with the {@link angular.Module} api. - */ - return function module(name, requires, configFn) { - var assertNotHasOwnProperty = function(name, context) { - if (name === 'hasOwnProperty') { - throw ngMinErr('badname', 'hasOwnProperty is not a valid {0} name', context); - } - }; - - assertNotHasOwnProperty(name, 'module'); - if (requires && modules.hasOwnProperty(name)) { - modules[name] = null; - } - return ensure(modules, name, function() { - if (!requires) { - throw $injectorMinErr('nomod', "Module '{0}' is not available! You either misspelled " + - "the module name or forgot to load it. If registering a module ensure that you " + - "specify the dependencies as the second argument.", name); - } - - /** @type {!Array.>} */ - var invokeQueue = []; - - /** @type {!Array.} */ - var configBlocks = []; - - /** @type {!Array.} */ - var runBlocks = []; - - var config = invokeLater('$injector', 'invoke', 'push', configBlocks); - - /** @type {angular.Module} */ - var moduleInstance = { - // Private state - _configBlocks: [], - _runBlocks: runBlocks, - - /** - * @ngdoc property - * @name angular.Module#requires - * @module ng - * @returns {Array.} List of module names which must be loaded before this module. - * @description - * Holds the list of modules which the injector will load before the current module is - * loaded. - */ - requires: requires, - - /** - * @ngdoc property - * @name angular.Module#name - * @module ng - * @returns {string} Name of the module. - * @description - */ - name: name, - - - /** - * @ngdoc method - * @name angular.Module#provider - * @module ng - * @param {string} name service name - * @param {Function} providerType Construction function for creating new instance of the - * service. - * @description - * See {@link auto.$provide#provider $provide.provider()}. - */ - provider: invokeLater('$provide', 'provider'), - - /** - * @ngdoc method - * @name angular.Module#factory - * @module ng - * @param {string} name service name - * @param {Function} providerFunction Function for creating new instance of the service. - * @description - * See {@link auto.$provide#factory $provide.factory()}. - */ - factory: invokeLater('$provide', 'factory'), - - /** - * @ngdoc method - * @name angular.Module#service - * @module ng - * @param {string} name service name - * @param {Function} constructor A constructor function that will be instantiated. - * @description - * See {@link auto.$provide#service $provide.service()}. - */ - service: invokeLater('$provide', 'service'), - - /** - * @ngdoc method - * @name angular.Module#value - * @module ng - * @param {string} name service name - * @param {*} object Service instance object. - * @description - * See {@link auto.$provide#value $provide.value()}. - */ - value: invokeLater('$provide', 'value'), - - /** - * @ngdoc method - * @name angular.Module#constant - * @module ng - * @param {string} name constant name - * @param {*} object Constant value. - * @description - * Because the constant are fixed, they get applied before other provide methods. - * See {@link auto.$provide#constant $provide.constant()}. - */ - constant: invokeLater('$provide', 'constant', 'unshift'), - - /** - * @ngdoc method - * @name angular.Module#animation - * @module ng - * @param {string} name animation name - * @param {Function} animationFactory Factory function for creating new instance of an - * animation. - * @description - * - * **NOTE**: animations take effect only if the **ngAnimate** module is loaded. - * - * - * Defines an animation hook that can be later used with - * {@link ngAnimate.$animate $animate} service and directives that use this service. - * - * ```js - * module.animation('.animation-name', function($inject1, $inject2) { - * return { - * eventName : function(element, done) { - * //code to run the animation - * //once complete, then run done() - * return function cancellationFunction(element) { - * //code to cancel the animation - * } - * } - * } - * }) - * ``` - * - * See {@link ngAnimate.$animateProvider#register $animateProvider.register()} and - * {@link ngAnimate ngAnimate module} for more information. - */ - animation: invokeLater('$animateProvider', 'register'), - - /** - * @ngdoc method - * @name angular.Module#filter - * @module ng - * @param {string} name Filter name. - * @param {Function} filterFactory Factory function for creating new instance of filter. - * @description - * See {@link ng.$filterProvider#register $filterProvider.register()}. - */ - filter: invokeLater('$filterProvider', 'register'), - - /** - * @ngdoc method - * @name angular.Module#controller - * @module ng - * @param {string|Object} name Controller name, or an object map of controllers where the - * keys are the names and the values are the constructors. - * @param {Function} constructor Controller constructor function. - * @description - * See {@link ng.$controllerProvider#register $controllerProvider.register()}. - */ - controller: invokeLater('$controllerProvider', 'register'), - - /** - * @ngdoc method - * @name angular.Module#directive - * @module ng - * @param {string|Object} name Directive name, or an object map of directives where the - * keys are the names and the values are the factories. - * @param {Function} directiveFactory Factory function for creating new instance of - * directives. - * @description - * See {@link ng.$compileProvider#directive $compileProvider.directive()}. - */ - directive: invokeLater('$compileProvider', 'directive'), - - /** - * @ngdoc method - * @name angular.Module#config - * @module ng - * @param {Function} configFn Execute this function on module load. Useful for service - * configuration. - * @description - * Use this method to register work which needs to be performed on module loading. - * For more about how to configure services, see - * {@link providers#providers_provider-recipe Provider Recipe}. - */ - config: config, - - /** - * @ngdoc method - * @name angular.Module#run - * @module ng - * @param {Function} initializationFn Execute this function after injector creation. - * Useful for application initialization. - * @description - * Use this method to register work which should be performed when the injector is done - * loading all modules. - */ - run: function(block) { - runBlocks.push(block); - return this; - } - }; - - /** - * ANGULAR HINT ALTERATION - * To make this loader compatible with apps that are running - * both Angular 1.2 and 1.3, the loader must handle 1.3 applications - * that expect to initialize their config blocks after all providers - * are registered. Hence, the configBlocks are added to the end - * of the exisiting invokeQueue. - */ - Object.defineProperty(moduleInstance, '_invokeQueue', { - get: function() { - return invokeQueue.concat(configBlocks); - } - }); - - if (configFn) { - config(configFn); - } - - return moduleInstance; - - /** - * @param {string} provider - * @param {string} method - * @param {String=} insertMethod - * @returns {angular.Module} - */ - function invokeLater(provider, method, insertMethod, queue) { - if (!queue) queue = invokeQueue; - return function() { - queue[insertMethod || 'push']([provider, method, arguments]); - return moduleInstance; - }; - } - }); - }; - }); - -} - -setupModuleLoader(window); -})(window); - -/** - * Closure compiler type information - * - * @typedef { { - * requires: !Array., - * invokeQueue: !Array.>, - * - * service: function(string, Function):angular.Module, - * factory: function(string, Function):angular.Module, - * value: function(string, *):angular.Module, - * - * filter: function(string, Function):angular.Module, - * - * init: function(Function):angular.Module - * } } - */ -angular.Module; - - -},{}],3:[function(require,module,exports){ -'use strict'; - -// Create pipe for all hint messages from different modules -require('./src/modules/hintEmitter'); - -// Load angular hint modules -require('./src/modules/controllers'); -// require('./src/modules/directives'); -// require('./src/modules/dom'); -require('./src/modules/events'); -// require('./src/modules/interpolation'); -require('./src/modules/modules'); -require('./src/modules/scopes'); - -// List of all possible modules -// The default ng-hint behavior loads all modules -var AVAILABLE_MODULES = [ - 'ngHintControllers', -// 'ngHintDirectives', -// 'ngHintDom', - 'ngHintEvents', -// 'ngHintInterpolation', - 'ngHintModules', - 'ngHintScopes' -]; - -var SEVERITY_WARNING = 2; - -// Determine whether this run is by protractor. -// If protractor is running, the bootstrap will already be deferred. -// In this case `resumeBootstrap` should be patched to load the hint modules. -if (window.name === 'NG_DEFER_BOOTSTRAP!') { - var originalResumeBootstrap; - Object.defineProperty(angular, 'resumeBootstrap', { - get: function() { - return function(modules) { - return originalResumeBootstrap.call(angular, modules.concat(loadModules())); - }; - }, - set: function(resumeBootstrap) { - originalResumeBootstrap = resumeBootstrap; - } - }); -} -//If this is not a test, defer bootstrapping -else { - window.name = 'NG_DEFER_BOOTSTRAP!'; - - // determine which modules to load and resume bootstrap - document.addEventListener('DOMContentLoaded', maybeBootstrap); -} - -function maybeBootstrap() { - // we don't know if angular is loaded - if (!angular.resumeBootstrap) { - return setTimeout(maybeBootstrap, 1); - } - - var modules = loadModules(); - angular.resumeBootstrap(modules); -} - -function loadModules() { - var modules = [], elt; - if (angular.version.minor < 2) { - return modules; - } - - if ((elt = document.querySelector('[ng-hint-include]'))) { - modules = hintModulesFromElement(elt); - } else if (elt = document.querySelector('[ng-hint-exclude]')) { - modules = excludeModules(hintModulesFromElement(elt)); - } else if (document.querySelector('[ng-hint]')) { - modules = AVAILABLE_MODULES; - } else { - angular.hint.emit('general:noinclude', 'ngHint is included on the page, but is not active because ' + - 'there is no `ng-hint` attribute present', SEVERITY_WARNING); - } - return modules; -} - -function excludeModules(modulesToExclude) { - return AVAILABLE_MODULES.filter(function(module) { - return modulesToExclude.indexOf(module) === -1; - }); -} - -function hintModulesFromElement (elt) { - var selectedModules = (elt.attributes['ng-hint-include'] || - elt.attributes['ng-hint-exclude']).value.split(' '); - - return selectedModules.map(hintModuleName).filter(function (name) { - return (AVAILABLE_MODULES.indexOf(name) > -1) || - angular.hint.emit('general:404module', 'Module ' + name + ' could not be found', SEVERITY_WARNING); - }); -} - -function hintModuleName(name) { - return 'ngHint' + title(name); -} - -function title(str) { - return str[0].toUpperCase() + str.substr(1); -} - -var LEVELS = [ - 'error', - 'warning', - 'suggestion' -]; - -},{"./src/modules/controllers":25,"./src/modules/events":26,"./src/modules/hintEmitter":27,"./src/modules/modules":28,"./src/modules/scopes":29}],4:[function(require,module,exports){ -module.exports = function debounceOn (fn, timeout, hash) { - var timeouts = {}; - - timeout = typeof timeout === 'number' ? timeout : (hash = timeout, 100); - hash = typeof hash === 'function' ? hash : defaultHash; - - return function () { - var key = hash.apply(null, arguments); - var args = arguments; - if (typeof timeouts[key] === 'undefined') { - timeouts[key] = setTimeout(function () { - delete timeouts[key]; - fn.apply(null, args); - }, timeout); - } - return function cancel () { - if (timeouts[key]) { - clearTimeout(timeouts[key]); - delete timeouts[key]; - return true; - } - return false; - }; - }; -}; - -function defaultHash () { - return Array.prototype.join.call(arguments, '::'); -} - -},{}],5:[function(require,module,exports){ -/*! - * EventEmitter2 - * https://github.com/hij1nx/EventEmitter2 - * - * Copyright (c) 2013 hij1nx - * Licensed under the MIT license. - */ -;!function(undefined) { - - var isArray = Array.isArray ? Array.isArray : function _isArray(obj) { - return Object.prototype.toString.call(obj) === "[object Array]"; - }; - var defaultMaxListeners = 10; - - function init() { - this._events = {}; - if (this._conf) { - configure.call(this, this._conf); - } - } - - function configure(conf) { - if (conf) { - - this._conf = conf; + this._conf = conf; conf.delimiter && (this.delimiter = conf.delimiter); conf.maxListeners && (this._events.maxListeners = conf.maxListeners); @@ -783,1325 +330,1776 @@ function defaultHash () { } else if (isArray(tree._listeners)) { - tree._listeners.push(listener); + tree._listeners.push(listener); + + if (!tree._listeners.warned) { + + var m = defaultMaxListeners; + + if (typeof this._events.maxListeners !== 'undefined') { + m = this._events.maxListeners; + } + + if (m > 0 && tree._listeners.length > m) { + + tree._listeners.warned = true; + console.error('(node) warning: possible EventEmitter memory ' + + 'leak detected. %d listeners added. ' + + 'Use emitter.setMaxListeners() to increase limit.', + tree._listeners.length); + console.trace(); + } + } + } + return true; + } + name = type.shift(); + } + return true; + } + + // By default EventEmitters will print a warning if more than + // 10 listeners are added to it. This is a useful default which + // helps finding memory leaks. + // + // Obviously not all Emitters should be limited to 10. This function allows + // that to be increased. Set to zero for unlimited. + + EventEmitter.prototype.delimiter = '.'; + + EventEmitter.prototype.setMaxListeners = function(n) { + this._events || init.call(this); + this._events.maxListeners = n; + if (!this._conf) this._conf = {}; + this._conf.maxListeners = n; + }; + + EventEmitter.prototype.event = ''; + + EventEmitter.prototype.once = function(event, fn) { + this.many(event, 1, fn); + return this; + }; + + EventEmitter.prototype.many = function(event, ttl, fn) { + var self = this; + + if (typeof fn !== 'function') { + throw new Error('many only accepts instances of Function'); + } + + function listener() { + if (--ttl === 0) { + self.off(event, listener); + } + fn.apply(this, arguments); + } + + listener._origin = fn; + + this.on(event, listener); + + return self; + }; + + EventEmitter.prototype.emit = function() { + + this._events || init.call(this); + + var type = arguments[0]; + + if (type === 'newListener' && !this.newListener) { + if (!this._events.newListener) { return false; } + } + + // Loop through the *_all* functions and invoke them. + if (this._all) { + var l = arguments.length; + var args = new Array(l - 1); + for (var i = 1; i < l; i++) args[i - 1] = arguments[i]; + for (i = 0, l = this._all.length; i < l; i++) { + this.event = type; + this._all[i].apply(this, args); + } + } + + // If there is no 'error' event listener then throw. + if (type === 'error') { + + if (!this._all && + !this._events.error && + !(this.wildcard && this.listenerTree.error)) { + + if (arguments[1] instanceof Error) { + throw arguments[1]; // Unhandled 'error' event + } else { + throw new Error("Uncaught, unspecified 'error' event."); + } + return false; + } + } + + var handler; + + if(this.wildcard) { + handler = []; + var ns = typeof type === 'string' ? type.split(this.delimiter) : type.slice(); + searchListenerTree.call(this, handler, ns, this.listenerTree, 0); + } + else { + handler = this._events[type]; + } + + if (typeof handler === 'function') { + this.event = type; + if (arguments.length === 1) { + handler.call(this); + } + else if (arguments.length > 1) + switch (arguments.length) { + case 2: + handler.call(this, arguments[1]); + break; + case 3: + handler.call(this, arguments[1], arguments[2]); + break; + // slower + default: + var l = arguments.length; + var args = new Array(l - 1); + for (var i = 1; i < l; i++) args[i - 1] = arguments[i]; + handler.apply(this, args); + } + return true; + } + else if (handler) { + var l = arguments.length; + var args = new Array(l - 1); + for (var i = 1; i < l; i++) args[i - 1] = arguments[i]; + + var listeners = handler.slice(); + for (var i = 0, l = listeners.length; i < l; i++) { + this.event = type; + listeners[i].apply(this, args); + } + return (listeners.length > 0) || !!this._all; + } + else { + return !!this._all; + } + + }; + + EventEmitter.prototype.on = function(type, listener) { + + if (typeof type === 'function') { + this.onAny(type); + return this; + } + + if (typeof listener !== 'function') { + throw new Error('on only accepts instances of Function'); + } + this._events || init.call(this); + + // To avoid recursion in the case that type == "newListeners"! Before + // adding it to the listeners, first emit "newListeners". + this.emit('newListener', type, listener); + + if(this.wildcard) { + growListenerTree.call(this, type, listener); + return this; + } + + if (!this._events[type]) { + // Optimize the case of one listener. Don't need the extra array object. + this._events[type] = listener; + } + else if(typeof this._events[type] === 'function') { + // Adding the second element, need to change to array. + this._events[type] = [this._events[type], listener]; + } + else if (isArray(this._events[type])) { + // If we've already got an array, just append. + this._events[type].push(listener); + + // Check for listener leak + if (!this._events[type].warned) { + + var m = defaultMaxListeners; + + if (typeof this._events.maxListeners !== 'undefined') { + m = this._events.maxListeners; + } + + if (m > 0 && this._events[type].length > m) { + + this._events[type].warned = true; + console.error('(node) warning: possible EventEmitter memory ' + + 'leak detected. %d listeners added. ' + + 'Use emitter.setMaxListeners() to increase limit.', + this._events[type].length); + console.trace(); + } + } + } + return this; + }; + + EventEmitter.prototype.onAny = function(fn) { + + if (typeof fn !== 'function') { + throw new Error('onAny only accepts instances of Function'); + } + + if(!this._all) { + this._all = []; + } + + // Add the function to the event listener collection. + this._all.push(fn); + return this; + }; + + EventEmitter.prototype.addListener = EventEmitter.prototype.on; + + EventEmitter.prototype.off = function(type, listener) { + if (typeof listener !== 'function') { + throw new Error('removeListener only takes instances of Function'); + } + + var handlers,leafs=[]; + + if(this.wildcard) { + var ns = typeof type === 'string' ? type.split(this.delimiter) : type.slice(); + leafs = searchListenerTree.call(this, null, ns, this.listenerTree, 0); + } + else { + // does not use listeners(), so no side effect of creating _events[type] + if (!this._events[type]) return this; + handlers = this._events[type]; + leafs.push({_listeners:handlers}); + } + + for (var iLeaf=0; iLeaf 0 && tree._listeners.length > m) { + if(this.wildcard) { + leaf._listeners.splice(position, 1); + } + else { + this._events[type].splice(position, 1); + } - tree._listeners.warned = true; - console.error('(node) warning: possible EventEmitter memory ' + - 'leak detected. %d listeners added. ' + - 'Use emitter.setMaxListeners() to increase limit.', - tree._listeners.length); - console.trace(); - } + if (handlers.length === 0) { + if(this.wildcard) { + delete leaf._listeners; + } + else { + delete this._events[type]; } } - return true; + return this; + } + else if (handlers === listener || + (handlers.listener && handlers.listener === listener) || + (handlers._origin && handlers._origin === listener)) { + if(this.wildcard) { + delete leaf._listeners; + } + else { + delete this._events[type]; + } } - name = type.shift(); } - return true; - } - - // By default EventEmitters will print a warning if more than - // 10 listeners are added to it. This is a useful default which - // helps finding memory leaks. - // - // Obviously not all Emitters should be limited to 10. This function allows - // that to be increased. Set to zero for unlimited. - - EventEmitter.prototype.delimiter = '.'; - EventEmitter.prototype.setMaxListeners = function(n) { - this._events || init.call(this); - this._events.maxListeners = n; - if (!this._conf) this._conf = {}; - this._conf.maxListeners = n; + return this; }; - EventEmitter.prototype.event = ''; - - EventEmitter.prototype.once = function(event, fn) { - this.many(event, 1, fn); + EventEmitter.prototype.offAny = function(fn) { + var i = 0, l = 0, fns; + if (fn && this._all && this._all.length > 0) { + fns = this._all; + for(i = 0, l = fns.length; i < l; i++) { + if(fn === fns[i]) { + fns.splice(i, 1); + return this; + } + } + } else { + this._all = []; + } return this; }; - EventEmitter.prototype.many = function(event, ttl, fn) { - var self = this; + EventEmitter.prototype.removeListener = EventEmitter.prototype.off; - if (typeof fn !== 'function') { - throw new Error('many only accepts instances of Function'); + EventEmitter.prototype.removeAllListeners = function(type) { + if (arguments.length === 0) { + !this._events || init.call(this); + return this; } - function listener() { - if (--ttl === 0) { - self.off(event, listener); + if(this.wildcard) { + var ns = typeof type === 'string' ? type.split(this.delimiter) : type.slice(); + var leafs = searchListenerTree.call(this, null, ns, this.listenerTree, 0); + + for (var iLeaf=0; iLeaf 1) - switch (arguments.length) { - case 2: - handler.call(this, arguments[1]); - break; - case 3: - handler.call(this, arguments[1], arguments[2]); - break; - // slower - default: - var l = arguments.length; - var args = new Array(l - 1); - for (var i = 1; i < l; i++) args[i - 1] = arguments[i]; - handler.apply(this, args); - } - return true; - } - else if (handler) { - var l = arguments.length; - var args = new Array(l - 1); - for (var i = 1; i < l; i++) args[i - 1] = arguments[i]; +var distance = require('./levenstein_distance'); - var listeners = handler.slice(); - for (var i = 0, l = listeners.length; i < l; i++) { - this.event = type; - listeners[i].apply(this, args); +function suggestDictionary(dict, opts) { + opts = opts || {}; + var threshold = opts.threshold || 0.5; + return function suggest(word) { + var length = word.length; + return dict.reduce(function (result, dictEntry) { + var score = distance(dictEntry, word); + if (result.score > score && score / length < threshold) { + result.score = score; + result.word = dictEntry; } - return (listeners.length > 0) || !!this._all; - } - else { - return !!this._all; - } - + return result; + }, { score: Infinity }).word; }; +} - EventEmitter.prototype.on = function(type, listener) { +suggestDictionary.distance = distance; - if (typeof type === 'function') { - this.onAny(type); - return this; - } +},{"./levenstein_distance":4}],6:[function(require,module,exports){ +'use strict'; - if (typeof listener !== 'function') { - throw new Error('on only accepts instances of Function'); - } - this._events || init.call(this); +var list = 'click submit mouseenter mouseleave mousemove mousedown mouseover mouseup dblclick keyup keydown keypress blur focus submit cut copy paste'.split(' '); - // To avoid recursion in the case that type == "newListeners"! Before - // adding it to the listeners, first emit "newListeners". - this.emit('newListener', type, listener); +module.exports = list.map(function(eventName) { + return 'ng' + eventName.charAt(0).toUpperCase() + eventName.substr(1); +}); - if(this.wildcard) { - growListenerTree.call(this, type, listener); - return this; - } +},{}],7:[function(require,module,exports){ +'use strict'; - if (!this._events[type]) { - // Optimize the case of one listener. Don't need the extra array object. - this._events[type] = listener; - } - else if(typeof this._events[type] === 'function') { - // Adding the second element, need to change to array. - this._events[type] = [this._events[type], listener]; - } - else if (isArray(this._events[type])) { - // If we've already got an array, just append. - this._events[type].push(listener); +module.exports = function summarizeModel (model) { - // Check for listener leak - if (!this._events[type].warned) { + if (model instanceof Array) { + return JSON.stringify(model.map(summarizeProperty)); + } else if (typeof model === 'object') { + return JSON.stringify(Object. + keys(model). + filter(isAngularPrivatePropertyName). + reduce(shallowSummary, {})); + } else { + return model; + } - var m = defaultMaxListeners; + function shallowSummary (obj, prop) { + obj[prop] = summarizeProperty(model[prop]); + return obj; + } +}; - if (typeof this._events.maxListeners !== 'undefined') { - m = this._events.maxListeners; - } +function isAngularPrivatePropertyName (key) { + return !(key[0] === '$' && key[1] === '$') && key !== '$parent' && key !== '$root'; +} - if (m > 0 && this._events[type].length > m) { +// TODO: handle DOM nodes, fns, etc better. +function summarizeProperty (obj) { + return obj instanceof Array ? + { '~array-length': obj.length } : + obj === null ? + null : + typeof obj === 'object' ? + { '~object': true } : + obj; +} - this._events[type].warned = true; - console.error('(node) warning: possible EventEmitter memory ' + - 'leak detected. %d listeners added. ' + - 'Use emitter.setMaxListeners() to increase limit.', - this._events[type].length); - console.trace(); - } - } - } - return this; - }; +},{}],8:[function(require,module,exports){ +var MODULE_NAME = 'Modules'; - EventEmitter.prototype.onAny = function(fn) { +module.exports = function(modules) { + modules.forEach(function(module) { + angular.hint.emit(MODULE_NAME, module.message, module.severity); + }); +}; - if (typeof fn !== 'function') { - throw new Error('onAny only accepts instances of Function'); - } +},{}],9:[function(require,module,exports){ +var modData = require('./moduleData'); + MODULE_NAME = 'Modules', + SEVERITY_WARNING = 2; - if(!this._all) { - this._all = []; - } +module.exports = function() { + var multiLoaded = []; + for(var modName in modData.createdMulti) { + var message = 'Multiple modules with name "' + modName + '" are being created and they will ' + + 'overwrite each other.'; + var multi = modData.createdMulti[modName]; + var multiLength = multi.length; + var details = { + existingModule: multi[multiLength - 1], + overwrittenModules: multi.slice(0, multiLength - 1) + }; + multiLoaded + .push({module: details, message: message, name: MODULE_NAME, severity: SEVERITY_WARNING}); + } + return multiLoaded; +}; - // Add the function to the event listener collection. - this._all.push(fn); - return this; - }; +},{"./moduleData":16}],10:[function(require,module,exports){ +var modData = require('./moduleData'); - EventEmitter.prototype.addListener = EventEmitter.prototype.on; +module.exports = function(moduleName, getCreated) { + return (getCreated)? modData.createdModules[moduleName] : modData.loadedModules[moduleName]; +}; - EventEmitter.prototype.off = function(type, listener) { - if (typeof listener !== 'function') { - throw new Error('removeListener only takes instances of Function'); - } +},{"./moduleData":16}],11:[function(require,module,exports){ +var MODULE_NAME = 'Modules', + SEVERITY_ERROR = 1; + module.exports = function(attrs, ngAppFound) { + if(attrs['ng-app'] && ngAppFound) { + angular.hint.emit(MODULE_NAME, 'ng-app may only be included once. The module "' + + attrs['ng-app'].value + '" was not used to bootstrap because ng-app was already included.', + SEVERITY_ERROR); + } + return attrs['ng-app'] ? attrs['ng-app'].value : undefined; + }; - var handlers,leafs=[]; - if(this.wildcard) { - var ns = typeof type === 'string' ? type.split(this.delimiter) : type.slice(); - leafs = searchListenerTree.call(this, null, ns, this.listenerTree, 0); - } - else { - // does not use listeners(), so no side effect of creating _events[type] - if (!this._events[type]) return this; - handlers = this._events[type]; - leafs.push({_listeners:handlers}); - } - for (var iLeaf=0; iLeaf 0) { - fns = this._all; - for(i = 0, l = fns.length; i < l; i++) { - if(fn === fns[i]) { - fns.splice(i, 1); - return this; - } - } - } else { - this._all = []; - } - return this; - }; +module.exports = function(str) { + if (str === 'ng') { + return true; + } + + if(str.charAt(0).toUpperCase() === str.charAt(0)) { + angular.hint.emit(MODULE_NAME, 'The best practice for' + + ' module names is to use dot.case or lowerCamelCase. Check the name of "' + str + '".', + SEVERITY_SUGGESTION); + return false; + } + if(str.toLowerCase() === str && str.indexOf('.') === -1) { + angular.hint.emit(MODULE_NAME, 'Module names should be namespaced' + + ' with a dot (app.dashboard) or lowerCamelCase (appDashboard). Check the name of "' + str + '".', SEVERITY_SUGGESTION); + return false; + } + return true; +}; - EventEmitter.prototype.removeListener = EventEmitter.prototype.off; +},{}],15:[function(require,module,exports){ +var normalizeAttribute = require('./normalizeAttribute'); - EventEmitter.prototype.removeAllListeners = function(type) { - if (arguments.length === 0) { - !this._events || init.call(this); - return this; +module.exports = function(attrs) { + for(var i = 0, length = attrs.length; i < length; i++) { + if(normalizeAttribute(attrs[i].nodeName) === 'ng-view' || + attrs[i].value.indexOf('ng-view') > -1) { + return true; } + } +}; - if(this.wildcard) { - var ns = typeof type === 'string' ? type.split(this.delimiter) : type.slice(); - var leafs = searchListenerTree.call(this, null, ns, this.listenerTree, 0); - - for (var iLeaf=0; iLeaf score && score / length < threshold) { - result.score = score; - result.word = dictEntry; - } - return result; - }, { score: Infinity }).word; - }; -} +// local state +var nameToControllerMap = {}; -suggestDictionary.distance = distance; +/** +* Decorates $controller with a patching function to +* log a message if the controller is instantiated on the window +*/ +angular.module('ngHintControllers', []). + config(['$provide', '$controllerProvider', function ($provide, $controllerProvider) { + $provide.decorator('$controller', ['$delegate', controllerDecorator]); -},{"./levenstein_distance":6}],8:[function(require,module,exports){ -'use strict'; + var originalRegister = $controllerProvider.register; + $controllerProvider.register = function(name, constructor) { + stringOrObjectRegister(name); + originalRegister.apply($controllerProvider, arguments); + } + }]); -var list = 'click submit mouseenter mouseleave mousemove mousedown mouseover mouseup dblclick keyup keydown keypress blur focus submit cut copy paste'.split(' '); +function controllerDecorator($delegate) { + return function(ctrl) { + if (typeof ctrl === 'string') { + var match = ctrl.match(CNTRL_REG); + var ctrlName = (match && match[1]) || ctrl; -module.exports = list.map(function(eventName) { - return 'ng' + eventName.charAt(0).toUpperCase() + eventName.substr(1); -}); + if (!nameToControllerMap[ctrlName]) { + sendMessageForControllerName(ctrlName); + } -},{}],9:[function(require,module,exports){ -'use strict'; + if (!nameToControllerMap[ctrlName] && typeof window[ctrlName] === 'function') { + sendMessageForGlobalController(ctrlName); + } + } + return $delegate.apply(this, arguments); + }; +} -module.exports = function summarizeModel (model) { +/** +* Save details of the controllers as they are instantiated +* for use in decoration. +* Hint about the best practices for naming controllers. +*/ +var originalModule = angular.module; - if (model instanceof Array) { - return JSON.stringify(model.map(summarizeProperty)); - } else if (typeof model === 'object') { - return JSON.stringify(Object. - keys(model). - filter(isAngularPrivatePropertyName). - reduce(shallowSummary, {})); +function stringOrObjectRegister(controllerName) { + if ((controllerName !== null) && (typeof controllerName === 'object')) { + Object.keys(controllerName).forEach(processController); } else { - return model; + processController(controllerName); } +} + +function processController(ctrlName) { + nameToControllerMap[ctrlName] = true; + sendMessageForControllerName(ctrlName); +} - function shallowSummary (obj, prop) { - obj[prop] = summarizeProperty(model[prop]); - return obj; +function sendMessageForGlobalController(name) { + angular.hint.emit(MODULE_NAME + ':global', + 'add `' + name + '` to a module', + angular.version.minor <= 2 ? SEVERITY_WARNING : SEVERITY_ERROR, + CATEGORY_GLOBAL_CONTROLLER); +} + +function sendMessageForControllerName(name) { + var newName = name; + if (!startsWithUpperCase(name)) { + newName = title(newName); } -}; + if (!endsWithController(name)) { + newName = addControllerSuffix(newName); + } + if (name !== newName) { + angular.hint.emit(MODULE_NAME + ':rename', + 'Consider renaming `' + name + '` to `' + newName + '`.', + SEVERITY_WARNING, + CATEGORY_CONTROLLER_NAME); + } +} -function isAngularPrivatePropertyName (key) { - return !(key[0] === '$' && key[1] === '$') && key !== '$parent' && key !== '$root'; +function startsWithUpperCase(name) { + var firstChar = name.charAt(0); + return firstChar === firstChar.toUpperCase() && + firstChar !== firstChar.toLowerCase(); } -// TODO: handle DOM nodes, fns, etc better. -function summarizeProperty (obj) { - return obj instanceof Array ? - { '~array-length': obj.length } : - obj === null ? - null : - typeof obj === 'object' ? - { '~object': true } : - obj; +function title (name) { + return name[0].toUpperCase() + name.substr(1); } -},{}],10:[function(require,module,exports){ -var MODULE_NAME = 'Modules'; +var CONTROLLER_RE = /Controller$/; +function endsWithController(name) { + return CONTROLLER_RE.test(name); +} -module.exports = function(modules) { - modules.forEach(function(module) { - angular.hint.emit(MODULE_NAME, module.message, module.severity); - }); -}; +var RE = /(Ctrl|Kontroller)?$/; +function addControllerSuffix(name) { + return name.replace(RE, 'Controller'); +} -},{}],11:[function(require,module,exports){ -var modData = require('./moduleData'); - MODULE_NAME = 'Modules', - SEVERITY_WARNING = 2; +/* + * decorate angular module API + */ -module.exports = function() { - var multiLoaded = []; - for(var modName in modData.createdMulti) { - var message = 'Multiple modules with name "' + modName + '" are being created and they will ' + - 'overwrite each other.'; - var multi = modData.createdMulti[modName]; - var multiLength = multi.length; - var details = { - existingModule: multi[multiLength - 1], - overwrittenModules: multi.slice(0, multiLength - 1) - }; - multiLoaded - .push({module: details, message: message, name: MODULE_NAME, severity: SEVERITY_WARNING}); - } - return multiLoaded; -}; +angular.module = function() { + var module = originalModule.apply(this, arguments), + originalController = module.controller; -},{"./moduleData":18}],12:[function(require,module,exports){ -var modData = require('./moduleData'); + module.controller = function(controllerName, controllerConstructor) { + stringOrObjectRegister(controllerName); + return originalController.apply(this, arguments); + }; -module.exports = function(moduleName, getCreated) { - return (getCreated)? modData.createdModules[moduleName] : modData.loadedModules[moduleName]; + return module; }; -},{"./moduleData":18}],13:[function(require,module,exports){ -var MODULE_NAME = 'Modules', - SEVERITY_ERROR = 1; - module.exports = function(attrs, ngAppFound) { - if(attrs['ng-app'] && ngAppFound) { - angular.hint.emit(MODULE_NAME, 'ng-app may only be included once. The module "' + - attrs['ng-app'].value + '" was not used to bootstrap because ng-app was already included.', - SEVERITY_ERROR); - } - return attrs['ng-app'] ? attrs['ng-app'].value : undefined; - }; - - +},{}],24:[function(require,module,exports){ +'use strict'; -},{}],14:[function(require,module,exports){ -var getModule = require('./getModule'), - dictionary = Object.keys(require('./moduleData').createdModules), - suggest = require('suggest-it')(dictionary), - SEVERITY_ERROR = 1; +/** +* Load necessary functions from /lib into variables. +*/ +var ngEventAttributes = require('../lib/event-directives'), + MODULE_NAME = 'Events'; -module.exports = function(loadedModules) { - var undeclaredModules = []; - for(var module in loadedModules) { - var cModule = getModule(module, true); - if(!cModule) { - var match = suggest(module), - suggestion = (match) ? '; Try: "'+match+'"' : '', - message = 'Module "'+module+'" was loaded but does not exist'+suggestion+'.'; +/* + * Remove string expressions except property accessors. + * ex. abc["def"] = "gef"; // `removeStringExp` will remove "gef" but not "def". + */ +function removeStringExp(str) { + return str.replace(/"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'/g, + function(match, pos, full) { + // this is our lookaround code so that our regex doesn't become so + // complicated. + if (pos !== 0 && (match.length + pos) !== full.length && + full[pos - 1] === '[' && full[pos + match.length] === ']') { + return match; + } + return ''; + }); +} - undeclaredModules.push({module: null, message: message, severity: SEVERITY_ERROR}); - } +var getFunctionNames = function(str) { + if (typeof str !== 'string') { + return []; } - return undeclaredModules; + // There are still a bunch of corner cases here where we aren't going to be able to handle + // but we shouldn't break the user's app and we should handle most common cases. + // example of corner cases: we can't check for properties inside of function + // arguments like `move(a.b.c)` with the current implementation + // or property accessors with parentheses in them + // like `prop["hello (world)"] = "test";`. + // To fully fix these issues we would need a full blown expression parser. + var results = removeStringExp(str.replace(/\s+/g, '')) + .replace(/\(.*?\)/g, '') + .split(/[\+\-\/\|\<\>\^=&!%~;]/g).map(function(x) { + if (isNaN(+x)) { + if (x.match(/\w+\(.*\)$/)){ + return x.substr(0, x.indexOf('(')); + } + return x; + } + }).filter(function(x){ + return x; + }); + return results; }; -},{"./getModule":12,"./moduleData":18,"suggest-it":7}],15:[function(require,module,exports){ -var getModule = require('./getModule'); +/** +* Decorate $provide in order to examine ng-event directives +* and hint about their effective use. +*/ +angular.module('ngHintEvents', []) + .config(['$provide', function($provide) { + for (var i = 0; i < ngEventAttributes.length; i++) { + try { + $provide.decorator(ngEventAttributes[i] + 'Directive', + ['$delegate', '$parse', ngEventDirectivesDecorator(ngEventAttributes[i])]); + } catch(e) {} + } + }]); -var IGNORED = ['ngHintControllers', 'ngHintDirectives', 'ngHintDom', 'ngHintEvents', - 'ngHintInterpolation', 'ngHintModules', 'ngHintScopes', 'ng', 'ngLocale', 'protractorBaseModule_'], - SEVERITY_WARNING = 2; +function ngEventDirectivesDecorator(ngEventAttrName) { + return function ($delegate, $parse) { + var originalCompileFn = $delegate[0].compile; -module.exports = function(createdModules) { - var unusedModules = []; - for(var module in createdModules) { - if(!getModule(module)) { - var cModule = createdModules[module], - message = 'Module "' + cModule.name + '" was created but never loaded.'; - if(IGNORED.indexOf(cModule.name) === -1) { - unusedModules.push({module: cModule, message: message, severity: SEVERITY_WARNING}); - } - } - } - return unusedModules; -}; + $delegate[0].compile = function(element, attrs, transclude) { + var linkFn = originalCompileFn.apply(this, arguments); -},{"./getModule":12}],16:[function(require,module,exports){ -var MODULE_NAME = 'Modules', - SEVERITY_SUGGESTION = 3; + return function ngEventHandler(scope, element, attrs) { + var boundFuncs = getFunctionNames(attrs[ngEventAttrName]); + boundFuncs.forEach(function(boundFn) { + var property, propChain, lastProp = ''; + while((property = boundFn.match(/^.+?([^\.\[])*/)) !== null) { + property = property[0]; + propChain = lastProp + property; + if ($parse(propChain)(scope) === undefined) { + angular.hint.emit(MODULE_NAME + ':undef', propChain + ' is undefined'); + } + boundFn = boundFn.replace(property, ''); + lastProp += property; + if(boundFn.charAt(0) === '.') { + lastProp += '.'; + boundFn = boundFn.substr(1); + } + } + }); -module.exports = function(str) { - if (str === 'ng') { - return true; + return linkFn.apply(this, arguments); + }; + }; + return $delegate; } +} - if(str.charAt(0).toUpperCase() === str.charAt(0)) { - angular.hint.emit(MODULE_NAME, 'The best practice for' + - ' module names is to use dot.case or lowerCamelCase. Check the name of "' + str + '".', - SEVERITY_SUGGESTION); - return false; - } - if(str.toLowerCase() === str && str.indexOf('.') === -1) { - angular.hint.emit(MODULE_NAME, 'Module names should be namespaced' + - ' with a dot (app.dashboard) or lowerCamelCase (appDashboard). Check the name of "' + str + '".', SEVERITY_SUGGESTION); - return false; - } - return true; -}; +},{"../lib/event-directives":6}],25:[function(require,module,exports){ +'use strict'; + +/** + * We use EventEmitter2 here in order to have scoped events + * For instance: + * hint.emit('scope:digest', { + */ +var EventEmitter2 = require('eventemitter2').EventEmitter2; + +angular.hint = new EventEmitter2({ + wildcard: true, + delimiter: ':' +}); +},{"eventemitter2":3}],26:[function(require,module,exports){ +'use strict'; + +var getModule = require('./angular-hint-modules/getModule'), + start = require('./angular-hint-modules/start'), + storeNgAppAndView = require('./angular-hint-modules/storeNgAppAndView'), + storeUsedModules = require('./angular-hint-modules/storeUsedModules'), + hasNameSpace = require('./angular-hint-modules/hasNameSpace'), + modData = require('./angular-hint-modules/moduleData'); -},{}],17:[function(require,module,exports){ -var normalizeAttribute = require('./normalizeAttribute'); +var doc = Array.prototype.slice.call(document.getElementsByTagName('*')), + originalAngularModule = angular.module, + modules = {}; -module.exports = function(attrs) { - for(var i = 0, length = attrs.length; i < length; i++) { - if(normalizeAttribute(attrs[i].nodeName) === 'ng-view' || - attrs[i].value.indexOf('ng-view') > -1) { - return true; - } - } -}; +storeNgAppAndView(doc); -},{"./normalizeAttribute":20}],18:[function(require,module,exports){ -module.exports = { - createdModules: {}, - createdMulti: {}, - loadedModules: {} -}; +angular.module = function(name, requiresOriginal) { + var module = originalAngularModule.apply(this, arguments), + name = module.name; -},{}],19:[function(require,module,exports){ -var modData = require('./moduleData'), - getModule = require('./getModule'); + module.requiresOriginal = requiresOriginal; + modules[name] = module; + var modToCheck = getModule(name, true); + //check arguments to determine if called as setter or getter + var modIsSetter = arguments.length > 1; -module.exports = function() { - if(modData.ngViewExists && !getModule('ngRoute')) { - return {message: 'Directive "ngView" was used in the application however "ngRoute" was not loaded into any module.'}; + if (modIsSetter) { + hasNameSpace(name); } -}; - -},{"./getModule":12,"./moduleData":18}],20:[function(require,module,exports){ -module.exports = function(attribute) { - return attribute.replace(/^(?:data|x)[-_:]/, '').replace(/[:_]/g, '-'); -}; - -},{}],21:[function(require,module,exports){ -var display = require('./display'), - formatMultiLoaded = require('./formatMultiLoaded'), - getUnusedModules = require('./getUnusedModules'), - getUndeclaredModules = require('./getUndeclaredModules'), - modData = require('./moduleData'), - ngViewNoNgRoute = require('./ngViewNoNgRoute'); -module.exports = function() { - var unusedModules = getUnusedModules(modData.createdModules), - undeclaredModules = getUndeclaredModules(modData.loadedModules), - multiLoaded = formatMultiLoaded(), - noNgRoute = ngViewNoNgRoute(); - if(unusedModules.length || undeclaredModules.length || multiLoaded.length || noNgRoute) { - var toSend = unusedModules.concat(undeclaredModules) - .concat(multiLoaded); - if(noNgRoute) { - toSend = toSend.concat(noNgRoute); + if(modToCheck && modToCheck.requiresOriginal !== module.requiresOriginal && modIsSetter) { + if(!modData.createdMulti[name]) { + modData.createdMulti[name] = [getModule(name,true)]; } - display(toSend); + modData.createdMulti[name].push(module); } + modData.createdModules[name] = module; + return module; }; -},{"./display":10,"./formatMultiLoaded":11,"./getUndeclaredModules":14,"./getUnusedModules":15,"./moduleData":18,"./ngViewNoNgRoute":19}],22:[function(require,module,exports){ -var modData = require('./moduleData'); +angular.module('ngHintModules', []).config(function() { + var ngAppMod = modules[modData.ngAppMod]; + storeUsedModules(ngAppMod, modules); + start(); +}); -module.exports = function(module, isNgAppMod) { - var name = module.name || module; - if(!isNgAppMod){ - module.requires.forEach(function(dependency){ - modData.loadedModules[dependency] = dependency; - }); - } - else { - modData.loadedModules[name] = name; - modData.ngAppMod = name; - } -}; +},{"./angular-hint-modules/getModule":10,"./angular-hint-modules/hasNameSpace":14,"./angular-hint-modules/moduleData":16,"./angular-hint-modules/start":19,"./angular-hint-modules/storeNgAppAndView":21,"./angular-hint-modules/storeUsedModules":22}],27:[function(require,module,exports){ +'use strict'; -},{"./moduleData":18}],23:[function(require,module,exports){ -var getNgAppMod = require('./getNgAppMod'), - inAttrsOrClasses = require('./inAttrsOrClasses'), - storeDependencies = require('./storeDependencies'), - modData = require('./moduleData'); +var summarize = require('../lib/summarize-model'); +var debounceOn = require('debounce-on'); -module.exports = function(doms) { - var bothFound, - ngViewFound, - elem, - isElemName, - isInAttrsOrClasses, - ngAppMod; +var hint = angular.hint; - for(var i = 0; i < doms.length; i++) { - elem = doms[i]; - var attributes = elem.attributes; - isElemName = elem.nodeName.toLowerCase() === 'ng-view'; - isInAttrsOrClasses = inAttrsOrClasses(attributes); +hint.emit = hint.emit || function () {}; - ngViewFound = isElemName || isInAttrsOrClasses; +module.exports = angular.module('ngHintScopes', []).config(['$provide', function ($provide) { + $provide.decorator('$rootScope', ['$delegate', '$parse', decorateRootScope]); + $provide.decorator('$compile', ['$delegate', decorateDollaCompile]); +}]); - ngAppMod = getNgAppMod(attributes, modData.ngAppFound); - modData.ngAppFound = modData.ngAppFound || ngAppMod; +function decorateRootScope($delegate, $parse) { - if(ngAppMod) { - storeDependencies(ngAppMod, true); - } - modData.ngViewExists = ngViewFound ? true : modData.ngViewExists; + var perf = window.performance || { now: function () { return 0; } }; - if(bothFound) { - break; - } - } -}; + var scopes = {}, + watching = {}; -},{"./getNgAppMod":13,"./inAttrsOrClasses":17,"./moduleData":18,"./storeDependencies":22}],24:[function(require,module,exports){ -var storeDependencies = require('./storeDependencies'); + var debouncedEmitModelChange = debounceOn(emitModelChange, 10); -var storeUsedModules = module.exports = function(module, modules){ - if(module) { - storeDependencies(module); - module.requires.forEach(function(modName) { - var mod = modules[modName]; - storeUsedModules(mod, modules); - }); - } -}; -},{"./storeDependencies":22}],25:[function(require,module,exports){ -'use strict'; + hint.watch = function (scopeId, path) { + path = typeof path === 'string' ? path.split('.') : path; -var MODULE_NAME = 'Controllers', - CNTRL_REG = /^(\S+)(\s+as\s+(\w+))?$/, - CATEGORY_CONTROLLER_NAME = 'Name controllers according to best practices', - CATEGORY_GLOBAL_CONTROLLER = 'Using global functions as controllers is against Angular best practices and depricated in Angular 1.3 and up', - SEVERITY_ERROR = 1, - SEVERITY_WARNING = 2; + if (!watching[scopeId]) { + watching[scopeId] = {}; + } -// local state -var nameToControllerMap = {}; + for (var i = 1, ii = path.length; i <= ii; i += 1) { + var partialPath = path.slice(0, i).join('.'); + if (watching[scopeId][partialPath]) { + continue; + } + var get = gettterer(scopeId, partialPath); + var value = summarize(get()); + watching[scopeId][partialPath] = { + get: get, + value: value + }; + hint.emit('model:change', { + id: scopeId, + path: partialPath, + value: value + }); + } + }; -/** -* Decorates $controller with a patching function to -* log a message if the controller is instantiated on the window -*/ -angular.module('ngHintControllers', []). - config(['$provide', '$controllerProvider', function ($provide, $controllerProvider) { - $provide.decorator('$controller', ['$delegate', controllerDecorator]); + hint.assign = function (scopeId, path, value) { + var scope; + if (scope = scopes[scopeId]) { + scope.$apply(function () { + return $parse(path).assign(scope, value); + }); + } + }; - var originalRegister = $controllerProvider.register; - $controllerProvider.register = function(name, constructor) { - stringOrObjectRegister(name); - originalRegister.apply($controllerProvider, arguments); + hint.inspectScope = function (scopeId) { + var scope; + if (scope = scopes[scopeId]) { + window.$scope = scope; } - }]); + }; -function controllerDecorator($delegate) { - return function(ctrl) { - if (typeof ctrl === 'string') { - var match = ctrl.match(CNTRL_REG); - var ctrlName = (match && match[1]) || ctrl; + hint.unwatch = function (scopeId, unwatchPath) { + Object.keys(watching[scopeId]). + forEach(function (path) { + if (path.indexOf(unwatchPath) === 0) { + delete watching[scopeId][path]; + } + }); + }; - if (!nameToControllerMap[ctrlName]) { - sendMessageForControllerName(ctrlName); - } + var scopePrototype = ('getPrototypeOf' in Object) ? + Object.getPrototypeOf($delegate) : $delegate.__proto__; - if (!nameToControllerMap[ctrlName] && typeof window[ctrlName] === 'function') { - sendMessageForGlobalController(ctrlName); - } + var _watch = scopePrototype.$watch; + var _digestEvents = []; + scopePrototype.$watch = function (watchExpression, reactionFunction) { + if (typeof watchExpression === 'string' && + isOneTimeBindExp(watchExpression)) { + return _watch.apply(this, arguments); + } + var watchStr = humanReadableWatchExpression(watchExpression); + var scopeId = this.$id; + if (typeof watchExpression === 'function') { + arguments[0] = function () { + var start = perf.now(); + var ret = watchExpression.apply(this, arguments); + var end = perf.now(); + _digestEvents.push({ + eventType: 'scope:watch', + id: scopeId, + watch: watchStr, + time: end - start + }); + return ret; + }; + } else { + var thatScope = this; + arguments[0] = function () { + var start = perf.now(); + var ret = thatScope.$eval(watchExpression); + var end = perf.now(); + _digestEvents.push({ + eventType: 'scope:watch', + id: scopeId, + watch: watchStr, + time: end - start + }); + return ret; + }; } - return $delegate.apply(this, arguments); - }; -} - -/** -* Save details of the controllers as they are instantiated -* for use in decoration. -* Hint about the best practices for naming controllers. -*/ -var originalModule = angular.module; -function stringOrObjectRegister(controllerName) { - if ((controllerName !== null) && (typeof controllerName === 'object')) { - Object.keys(controllerName).forEach(processController); - } else { - processController(controllerName); - } -} + if (typeof reactionFunction === 'function') { + arguments[1] = function () { + var start = perf.now(); + var ret = reactionFunction.apply(this, arguments); + var end = perf.now(); + _digestEvents.push({ + eventType: 'scope:reaction', + id: this.$id, + watch: watchStr, + time: end - start + }); + return ret; + }; + } -function processController(ctrlName) { - nameToControllerMap[ctrlName] = true; - sendMessageForControllerName(ctrlName); -} + return _watch.apply(this, arguments); + }; -function sendMessageForGlobalController(name) { - angular.hint.emit(MODULE_NAME + ':global', - 'add `' + name + '` to a module', - angular.version.minor <= 2 ? SEVERITY_WARNING : SEVERITY_ERROR, - CATEGORY_GLOBAL_CONTROLLER); -} + var _digest = scopePrototype.$digest; + scopePrototype.$digest = function (fn) { + _digestEvents = []; + var start = perf.now(); + var ret = _digest.apply(this, arguments); + var end = perf.now(); + hint.emit('scope:digest', { + id: this.$id, + time: end - start, + events: _digestEvents + }); + return ret; + }; -function sendMessageForControllerName(name) { - var newName = name; - if (!startsWithUpperCase(name)) { - newName = title(newName); - } - if (!endsWithController(name)) { - newName = addControllerSuffix(newName); - } - if (name !== newName) { - angular.hint.emit(MODULE_NAME + ':rename', - 'Consider renaming `' + name + '` to `' + newName + '`.', - SEVERITY_WARNING, - CATEGORY_CONTROLLER_NAME); - } -} + var _destroy = scopePrototype.$destroy; + scopePrototype.$destroy = function () { + var id = this.$id; -function startsWithUpperCase(name) { - var firstChar = name.charAt(0); - return firstChar === firstChar.toUpperCase() && - firstChar !== firstChar.toLowerCase(); -} + hint.emit('scope:destroy', { id: id }); -function title (name) { - return name[0].toUpperCase() + name.substr(1); -} + delete scopes[id]; + delete watching[id]; -var CONTROLLER_RE = /Controller$/; -function endsWithController(name) { - return CONTROLLER_RE.test(name); -} + return _destroy.apply(this, arguments); + }; -var RE = /(Ctrl|Kontroller)?$/; -function addControllerSuffix(name) { - return name.replace(RE, 'Controller'); -} -/* - * decorate angular module API - */ + var _new = scopePrototype.$new; + scopePrototype.$new = function () { + var child = _new.apply(this, arguments); -angular.module = function() { - var module = originalModule.apply(this, arguments), - originalController = module.controller; + scopes[child.$id] = child; + watching[child.$id] = {}; - module.controller = function(controllerName, controllerConstructor) { - stringOrObjectRegister(controllerName); - return originalController.apply(this, arguments); + hint.emit('scope:new', { parent: this.$id, child: child.$id }); + setTimeout(function () { + emitScopeElt(child); + }, 0); + return child; }; - return module; -}; - -},{}],26:[function(require,module,exports){ -'use strict'; - -/** -* Load necessary functions from /lib into variables. -*/ -var ngEventAttributes = require('../lib/event-directives'), - MODULE_NAME = 'Events'; - -/* - * Remove string expressions except property accessors. - * ex. abc["def"] = "gef"; // `removeStringExp` will remove "gef" but not "def". - */ -function removeStringExp(str) { - return str.replace(/"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'/g, - function(match, pos, full) { - // this is our lookaround code so that our regex doesn't become so - // complicated. - if (pos !== 0 && (match.length + pos) !== full.length && - full[pos - 1] === '[' && full[pos + match.length] === ']') { - return match; - } - return ''; + function emitScopeElt (scope) { + var scopeId = scope.$id; + var elt = findElt(scopeId); + var descriptor = scopeDescriptor(elt, scope); + hint.emit('scope:link', { + id: scopeId, + descriptor: descriptor }); -} - -var getFunctionNames = function(str) { - if (typeof str !== 'string') { - return []; } - // There are still a bunch of corner cases here where we aren't going to be able to handle - // but we shouldn't break the user's app and we should handle most common cases. - // example of corner cases: we can't check for properties inside of function - // arguments like `move(a.b.c)` with the current implementation - // or property accessors with parentheses in them - // like `prop["hello (world)"] = "test";`. - // To fully fix these issues we would need a full blown expression parser. - var results = removeStringExp(str.replace(/\s+/g, '')) - .replace(/\(.*?\)/g, '') - .split(/[\+\-\/\|\<\>\^=&!%~;]/g).map(function(x) { - if (isNaN(+x)) { - if (x.match(/\w+\(.*\)$/)){ - return x.substr(0, x.indexOf('(')); - } - return x; - } - }).filter(function(x){ - return x; - }); - return results; -}; -/** -* Decorate $provide in order to examine ng-event directives -* and hint about their effective use. -*/ -angular.module('ngHintEvents', []) - .config(['$provide', function($provide) { - for (var i = 0; i < ngEventAttributes.length; i++) { - try { - $provide.decorator(ngEventAttributes[i] + 'Directive', - ['$delegate', '$parse', ngEventDirectivesDecorator(ngEventAttributes[i])]); - } catch(e) {} - } - }]); + function findElt (scopeId) { + var elts = document.querySelectorAll('.ng-scope'); + var elt, scope; -function ngEventDirectivesDecorator(ngEventAttrName) { - return function ($delegate, $parse) { - var originalCompileFn = $delegate[0].compile; + for (var i = 0; i < elts.length; i++) { + elt = angular.element(elts[i]); + scope = elt.scope(); + if (scope.$id === scopeId) { + return elt; + } + } + } - $delegate[0].compile = function(element, attrs, transclude) { - var linkFn = originalCompileFn.apply(this, arguments); + var _apply = scopePrototype.$apply; + scopePrototype.$apply = function (fn) { + // var start = perf.now(); + var ret = _apply.apply(this, arguments); + // var end = perf.now(); + // hint.emit('scope:apply', { id: this.$id, time: end - start }); + debouncedEmitModelChange(); + return ret; + }; - return function ngEventHandler(scope, element, attrs) { - var boundFuncs = getFunctionNames(attrs[ngEventAttrName]); - boundFuncs.forEach(function(boundFn) { - var property, propChain, lastProp = ''; - while((property = boundFn.match(/^.+?([^\.\[])*/)) !== null) { - property = property[0]; - propChain = lastProp + property; - if ($parse(propChain)(scope) === undefined) { - angular.hint.emit(MODULE_NAME + ':undef', propChain + ' is undefined'); - } - boundFn = boundFn.replace(property, ''); - lastProp += property; - if(boundFn.charAt(0) === '.') { - lastProp += '.'; - boundFn = boundFn.substr(1); - } - } - }); - return linkFn.apply(this, arguments); + function gettterer (scopeId, path) { + if (path === '') { + return function () { + return scopes[scopeId]; }; + } + var getter = $parse(path); + return function () { + return getter(scopes[scopeId]); }; - return $delegate; } -} -},{"../lib/event-directives":8}],27:[function(require,module,exports){ -'use strict'; + function emitModelChange () { + Object.keys(watching).forEach(function (scopeId) { + Object.keys(watching[scopeId]).forEach(function (path) { + var model = watching[scopeId][path]; + var value = summarize(model.get()); + if (value !== model.value) { + hint.emit('model:change', { + id: (angular.version.minor < 3) ? scopeId : parseInt(scopeId), + path: path, + oldValue: model.value, + value: value + }); + model.value = value; + } + }); + }); + } -/** - * We use EventEmitter2 here in order to have scoped events - * For instance: - * hint.emit('scope:digest', { - */ -var EventEmitter2 = require('eventemitter2').EventEmitter2; + hint.emit('scope:new', { + parent: null, + child: $delegate.$id + }); + scopes[$delegate.$id] = $delegate; + watching[$delegate.$id] = {}; -angular.hint = new EventEmitter2({ - wildcard: true, - delimiter: ':' -}); -},{"eventemitter2":5}],28:[function(require,module,exports){ -'use strict'; + return $delegate; +} -var getModule = require('./angular-hint-modules/getModule'), - start = require('./angular-hint-modules/start'), - storeNgAppAndView = require('./angular-hint-modules/storeNgAppAndView'), - storeUsedModules = require('./angular-hint-modules/storeUsedModules'), - hasNameSpace = require('./angular-hint-modules/hasNameSpace'), - modData = require('./angular-hint-modules/moduleData'); +function decorateDollaCompile ($delegate) { + var newCompile = function () { + var link = $delegate.apply(this, arguments); -var doc = Array.prototype.slice.call(document.getElementsByTagName('*')), - originalAngularModule = angular.module, - modules = {}; + return function (scope) { + var elt = link.apply(this, arguments); + var descriptor = scopeDescriptor(elt, scope); + hint.emit('scope:link', { + id: scope.$id, + descriptor: descriptor + }); + return elt; + }; + }; -storeNgAppAndView(doc); + // TODO: test this + // copy private helpers like $$addScopeInfo + for (var prop in $delegate) { + if ($delegate.hasOwnProperty(prop)) { + newCompile[prop] = $delegate[prop]; + } + } + return newCompile; +} -angular.module = function(name, requiresOriginal) { - var module = originalAngularModule.apply(this, arguments), - name = module.name; +var TYPES = [ + 'ng-app', + 'ng-controller', + 'ng-repeat', + 'ng-include' +]; - module.requiresOriginal = requiresOriginal; - modules[name] = module; - var modToCheck = getModule(name, true); - //check arguments to determine if called as setter or getter - var modIsSetter = arguments.length > 1; +function scopeDescriptor (elt, scope) { + var val, + theseTypes = [], + type; - if (modIsSetter) { - hasNameSpace(name); + if (elt) { + for (var i = 0, ii = TYPES.length; i < ii; i++) { + type = TYPES[i]; + if (val = elt.attr(type)) { + theseTypes.push(type + '="' + val + '"'); + } + } + } + if (theseTypes.length === 0) { + return 'scope.$id=' + scope.$id; + } else { + return theseTypes.join(' '); } +} - if(modToCheck && modToCheck.requiresOriginal !== module.requiresOriginal && modIsSetter) { - if(!modData.createdMulti[name]) { - modData.createdMulti[name] = [getModule(name,true)]; - } - modData.createdMulti[name].push(module); +function humanReadableWatchExpression (fn) { + if (fn == null) { + return null; } - modData.createdModules[name] = module; - return module; -}; + if (fn.exp) { + fn = fn.exp; + } else if (fn.name) { + fn = fn.name; + } + return fn.toString(); +} -angular.module('ngHintModules', []).config(function() { - var ngAppMod = modules[modData.ngAppMod]; - storeUsedModules(ngAppMod, modules); - start(); +function isOneTimeBindExp(exp) { + // this is the same code angular 1.3.15 has to check + // for a one time bind expression + return exp.charAt(0) === ':' && exp.charAt(1) === ':'; +} + +},{"../lib/summarize-model":7,"debounce-on":2}],28:[function(require,module,exports){ +/* + * Batarang instrumentation + * + * This gets loaded into the context of the app you are inspecting + */ +require('./loader.js'); +require('angular-hint'); + +angular.hint.onAny(function (data, severity) { + window.postMessage({ + __fromBatarang: true, + module: this.event.split(':')[0], + event: this.event, + data: data, + severity: severity + }, '*'); }); -},{"./angular-hint-modules/getModule":12,"./angular-hint-modules/hasNameSpace":16,"./angular-hint-modules/moduleData":18,"./angular-hint-modules/start":21,"./angular-hint-modules/storeNgAppAndView":23,"./angular-hint-modules/storeUsedModules":24}],29:[function(require,module,exports){ -'use strict'; +},{"./loader.js":29,"angular-hint":1}],29:[function(require,module,exports){ +/** + * @license AngularJS v1.3.0-build.3042+sha.76e57a7 + * (c) 2010-2014 Google, Inc. http://angularjs.org + * License: MIT + */ -var summarize = require('../lib/summarize-model'); -var debounceOn = require('debounce-on'); +(function() {'use strict'; -var hint = angular.hint; +/** + * @description + * + * This object provides a utility for producing rich Error messages within + * Angular. It can be called as follows: + * + * var exampleMinErr = minErr('example'); + * throw exampleMinErr('one', 'This {0} is {1}', foo, bar); + * + * The above creates an instance of minErr in the example namespace. The + * resulting error will have a namespaced error code of example.one. The + * resulting error will replace {0} with the value of foo, and {1} with the + * value of bar. The object is not restricted in the number of arguments it can + * take. + * + * If fewer arguments are specified than necessary for interpolation, the extra + * interpolation markers will be preserved in the final string. + * + * Since data will be parsed statically during a build step, some restrictions + * are applied with respect to how minErr instances are created and called. + * Instances should have names of the form namespaceMinErr for a minErr created + * using minErr('namespace') . Error codes, namespaces and template strings + * should all be static strings, not variables or general expressions. + * + * @param {string} module The namespace to use for the new minErr instance. + * @returns {function(code:string, template:string, ...templateArgs): Error} minErr instance + */ -hint.emit = hint.emit || function () {}; +function minErr(module) { + return function () { + var code = arguments[0], + prefix = '[' + (module ? module + ':' : '') + code + '] ', + template = arguments[1], + templateArgs = arguments, + stringify = function (obj) { + if (typeof obj === 'function') { + return obj.toString().replace(/ \{[\s\S]*$/, ''); + } else if (typeof obj === 'undefined') { + return 'undefined'; + } else if (typeof obj !== 'string') { + return JSON.stringify(obj); + } + return obj; + }, + message, i; -module.exports = angular.module('ngHintScopes', []).config(['$provide', function ($provide) { - $provide.decorator('$rootScope', ['$delegate', '$parse', decorateRootScope]); - $provide.decorator('$compile', ['$delegate', decorateDollaCompile]); -}]); + message = prefix + template.replace(/\{\d+\}/g, function (match) { + var index = +match.slice(1, -1), arg; -function decorateRootScope($delegate, $parse) { + if (index + 2 < templateArgs.length) { + arg = templateArgs[index + 2]; + if (typeof arg === 'function') { + return arg.toString().replace(/ ?\{[\s\S]*$/, ''); + } else if (typeof arg === 'undefined') { + return 'undefined'; + } else if (typeof arg !== 'string') { + return toJson(arg); + } + return arg; + } + return match; + }); - var perf = window.performance || { now: function () { return 0; } }; + message = message + '\nhttp://errors.angularjs.org/1.3.0-build.3042+sha.76e57a7/' + + (module ? module + '/' : '') + code; + for (i = 2; i < arguments.length; i++) { + message = message + (i == 2 ? '?' : '&') + 'p' + (i-2) + '=' + + encodeURIComponent(stringify(arguments[i])); + } - var scopes = {}, - watching = {}; + return new Error(message); + }; +} - var debouncedEmitModelChange = debounceOn(emitModelChange, 10, byScopeId); +/** + * @ngdoc type + * @name angular.Module + * @module ng + * @description + * + * Interface for configuring angular {@link angular.module modules}. + */ - hint.watch = function (scopeId, path) { - path = typeof path === 'string' ? path.split('.') : path; +function setupModuleLoader(window) { - if (!watching[scopeId]) { - watching[scopeId] = {}; - } + var $injectorMinErr = minErr('$injector'); + var ngMinErr = minErr('ng'); - for (var i = 1, ii = path.length; i <= ii; i += 1) { - var partialPath = path.slice(0, i).join('.'); - if (watching[scopeId][partialPath]) { - continue; - } - var get = gettterer(scopeId, partialPath); - var value = summarize(get()); - watching[scopeId][partialPath] = { - get: get, - value: value - }; - hint.emit('model:change', { - id: scopeId, - path: partialPath, - value: value - }); - } - }; + function ensure(obj, name, factory) { + return obj[name] || (obj[name] = factory()); + } - hint.assign = function (scopeId, path, value) { - var scope; - if (scope = scopes[scopeId]) { - scope.$apply(function () { - return $parse(path).assign(scope, value); - }); - } - }; + var angular = ensure(window, 'angular', Object); - hint.inspectScope = function (scopeId) { - var scope; - if (scope = scopes[scopeId]) { - window.$scope = scope; - } - }; + // We need to expose `angular.$$minErr` to modules such as `ngResource` that reference it during bootstrap + angular.$$minErr = angular.$$minErr || minErr; - hint.unwatch = function (scopeId, unwatchPath) { - Object.keys(watching[scopeId]). - forEach(function (path) { - if (path.indexOf(unwatchPath) === 0) { - delete watching[scopeId][path]; + return ensure(angular, 'module', function() { + /** @type {Object.} */ + var modules = {}; + + /** + * @ngdoc function + * @name angular.module + * @module ng + * @description + * + * The `angular.module` is a global place for creating, registering and retrieving Angular + * modules. + * All modules (angular core or 3rd party) that should be available to an application must be + * registered using this mechanism. + * + * When passed two or more arguments, a new module is created. If passed only one argument, an + * existing module (the name passed as the first argument to `module`) is retrieved. + * + * + * # Module + * + * A module is a collection of services, directives, controllers, filters, and configuration information. + * `angular.module` is used to configure the {@link auto.$injector $injector}. + * + * ```js + * // Create a new module + * var myModule = angular.module('myModule', []); + * + * // register a new service + * myModule.value('appName', 'MyCoolApp'); + * + * // configure existing services inside initialization blocks. + * myModule.config(['$locationProvider', function($locationProvider) { + * // Configure existing providers + * $locationProvider.hashPrefix('!'); + * }]); + * ``` + * + * Then you can create an injector and load your modules like this: + * + * ```js + * var injector = angular.injector(['ng', 'myModule']) + * ``` + * + * However it's more likely that you'll just use + * {@link ng.directive:ngApp ngApp} or + * {@link angular.bootstrap} to simplify this process for you. + * + * @param {!string} name The name of the module to create or retrieve. + * @param {!Array.=} requires If specified then new module is being created. If + * unspecified then the module is being retrieved for further configuration. + * @param {Function=} configFn Optional configuration function for the module. Same as + * {@link angular.Module#config Module#config()}. + * @returns {module} new module with the {@link angular.Module} api. + */ + return function module(name, requires, configFn) { + var assertNotHasOwnProperty = function(name, context) { + if (name === 'hasOwnProperty') { + throw ngMinErr('badname', 'hasOwnProperty is not a valid {0} name', context); } - }); - }; + }; - var scopePrototype = ('getPrototypeOf' in Object) ? - Object.getPrototypeOf($delegate) : $delegate.__proto__; + assertNotHasOwnProperty(name, 'module'); + if (requires && modules.hasOwnProperty(name)) { + modules[name] = null; + } + return ensure(modules, name, function() { + if (!requires) { + throw $injectorMinErr('nomod', "Module '{0}' is not available! You either misspelled " + + "the module name or forgot to load it. If registering a module ensure that you " + + "specify the dependencies as the second argument.", name); + } - var _watch = scopePrototype.$watch; - var _digestEvents = []; - scopePrototype.$watch = function (watchExpression, reactionFunction) { - if (typeof watchExpression === 'string' && - isOneTimeBindExp(watchExpression)) { - return _watch.apply(this, arguments); - } - var watchStr = humanReadableWatchExpression(watchExpression); - var scopeId = this.$id; - if (typeof watchExpression === 'function') { - arguments[0] = function () { - var start = perf.now(); - var ret = watchExpression.apply(this, arguments); - var end = perf.now(); - _digestEvents.push({ - eventType: 'scope:watch', - id: scopeId, - watch: watchStr, - time: end - start - }); - return ret; - }; - } else { - var thatScope = this; - arguments[0] = function () { - var start = perf.now(); - var ret = thatScope.$eval(watchExpression); - var end = perf.now(); - _digestEvents.push({ - eventType: 'scope:watch', - id: scopeId, - watch: watchStr, - time: end - start - }); - return ret; - }; - } + /** @type {!Array.>} */ + var invokeQueue = []; - if (typeof reactionFunction === 'function') { - arguments[1] = function () { - var start = perf.now(); - var ret = reactionFunction.apply(this, arguments); - var end = perf.now(); - _digestEvents.push({ - eventType: 'scope:reaction', - id: this.$id, - watch: watchStr, - time: end - start - }); - return ret; - }; - } + /** @type {!Array.} */ + var configBlocks = []; - return _watch.apply(this, arguments); - }; + /** @type {!Array.} */ + var runBlocks = []; - var _digest = scopePrototype.$digest; - scopePrototype.$digest = function (fn) { - _digestEvents = []; - var start = perf.now(); - var ret = _digest.apply(this, arguments); - var end = perf.now(); - hint.emit('scope:digest', { - id: this.$id, - time: end - start, - events: _digestEvents - }); - return ret; - }; + var config = invokeLater('$injector', 'invoke', 'push', configBlocks); - var _destroy = scopePrototype.$destroy; - scopePrototype.$destroy = function () { - var id = this.$id; + /** @type {angular.Module} */ + var moduleInstance = { + // Private state + _configBlocks: [], + _runBlocks: runBlocks, - hint.emit('scope:destroy', { id: id }); + /** + * @ngdoc property + * @name angular.Module#requires + * @module ng + * @returns {Array.} List of module names which must be loaded before this module. + * @description + * Holds the list of modules which the injector will load before the current module is + * loaded. + */ + requires: requires, - delete scopes[id]; - delete watching[id]; + /** + * @ngdoc property + * @name angular.Module#name + * @module ng + * @returns {string} Name of the module. + * @description + */ + name: name, - return _destroy.apply(this, arguments); - }; + /** + * @ngdoc method + * @name angular.Module#provider + * @module ng + * @param {string} name service name + * @param {Function} providerType Construction function for creating new instance of the + * service. + * @description + * See {@link auto.$provide#provider $provide.provider()}. + */ + provider: invokeLater('$provide', 'provider'), - var _new = scopePrototype.$new; - scopePrototype.$new = function () { - var child = _new.apply(this, arguments); + /** + * @ngdoc method + * @name angular.Module#factory + * @module ng + * @param {string} name service name + * @param {Function} providerFunction Function for creating new instance of the service. + * @description + * See {@link auto.$provide#factory $provide.factory()}. + */ + factory: invokeLater('$provide', 'factory'), - scopes[child.$id] = child; - watching[child.$id] = {}; + /** + * @ngdoc method + * @name angular.Module#service + * @module ng + * @param {string} name service name + * @param {Function} constructor A constructor function that will be instantiated. + * @description + * See {@link auto.$provide#service $provide.service()}. + */ + service: invokeLater('$provide', 'service'), - hint.emit('scope:new', { parent: this.$id, child: child.$id }); - setTimeout(function () { - emitScopeElt(child); - }, 0); - return child; - }; + /** + * @ngdoc method + * @name angular.Module#value + * @module ng + * @param {string} name service name + * @param {*} object Service instance object. + * @description + * See {@link auto.$provide#value $provide.value()}. + */ + value: invokeLater('$provide', 'value'), - function emitScopeElt (scope) { - var scopeId = scope.$id; - var elt = findElt(scopeId); - var descriptor = scopeDescriptor(elt, scope); - hint.emit('scope:link', { - id: scopeId, - descriptor: descriptor - }); - } + /** + * @ngdoc method + * @name angular.Module#constant + * @module ng + * @param {string} name constant name + * @param {*} object Constant value. + * @description + * Because the constant are fixed, they get applied before other provide methods. + * See {@link auto.$provide#constant $provide.constant()}. + */ + constant: invokeLater('$provide', 'constant', 'unshift'), - function findElt (scopeId) { - var elts = document.querySelectorAll('.ng-scope'); - var elt, scope; + /** + * @ngdoc method + * @name angular.Module#animation + * @module ng + * @param {string} name animation name + * @param {Function} animationFactory Factory function for creating new instance of an + * animation. + * @description + * + * **NOTE**: animations take effect only if the **ngAnimate** module is loaded. + * + * + * Defines an animation hook that can be later used with + * {@link ngAnimate.$animate $animate} service and directives that use this service. + * + * ```js + * module.animation('.animation-name', function($inject1, $inject2) { + * return { + * eventName : function(element, done) { + * //code to run the animation + * //once complete, then run done() + * return function cancellationFunction(element) { + * //code to cancel the animation + * } + * } + * } + * }) + * ``` + * + * See {@link ngAnimate.$animateProvider#register $animateProvider.register()} and + * {@link ngAnimate ngAnimate module} for more information. + */ + animation: invokeLater('$animateProvider', 'register'), - for (var i = 0; i < elts.length; i++) { - elt = angular.element(elts[i]); - scope = elt.scope(); - if (scope.$id === scopeId) { - return elt; - } - } - } + /** + * @ngdoc method + * @name angular.Module#filter + * @module ng + * @param {string} name Filter name. + * @param {Function} filterFactory Factory function for creating new instance of filter. + * @description + * See {@link ng.$filterProvider#register $filterProvider.register()}. + */ + filter: invokeLater('$filterProvider', 'register'), - var _apply = scopePrototype.$apply; - scopePrototype.$apply = function (fn) { - // var start = perf.now(); - var ret = _apply.apply(this, arguments); - // var end = perf.now(); - // hint.emit('scope:apply', { id: this.$id, time: end - start }); - debouncedEmitModelChange(this); - return ret; - }; + /** + * @ngdoc method + * @name angular.Module#controller + * @module ng + * @param {string|Object} name Controller name, or an object map of controllers where the + * keys are the names and the values are the constructors. + * @param {Function} constructor Controller constructor function. + * @description + * See {@link ng.$controllerProvider#register $controllerProvider.register()}. + */ + controller: invokeLater('$controllerProvider', 'register'), + /** + * @ngdoc method + * @name angular.Module#directive + * @module ng + * @param {string|Object} name Directive name, or an object map of directives where the + * keys are the names and the values are the factories. + * @param {Function} directiveFactory Factory function for creating new instance of + * directives. + * @description + * See {@link ng.$compileProvider#directive $compileProvider.directive()}. + */ + directive: invokeLater('$compileProvider', 'directive'), - function gettterer (scopeId, path) { - if (path === '') { - return function () { - return scopes[scopeId]; - }; - } - var getter = $parse(path); - return function () { - return getter(scopes[scopeId]); - }; - } + /** + * @ngdoc method + * @name angular.Module#config + * @module ng + * @param {Function} configFn Execute this function on module load. Useful for service + * configuration. + * @description + * Use this method to register work which needs to be performed on module loading. + * For more about how to configure services, see + * {@link providers#providers_provider-recipe Provider Recipe}. + */ + config: config, - function emitModelChange (scope) { - var scopeId = scope.$id; - if (watching[scopeId]) { - Object.keys(watching[scopeId]).forEach(function (path) { - var model = watching[scopeId][path]; - var value = summarize(model.get()); - if (value !== model.value) { - hint.emit('model:change', { - id: scope.$id, - path: path, - oldValue: model.value, - value: value - }); - model.value = value; - } - }); - } - } + /** + * @ngdoc method + * @name angular.Module#run + * @module ng + * @param {Function} initializationFn Execute this function after injector creation. + * Useful for application initialization. + * @description + * Use this method to register work which should be performed when the injector is done + * loading all modules. + */ + run: function(block) { + runBlocks.push(block); + return this; + } + }; - hint.emit('scope:new', { - parent: null, - child: $delegate.$id - }); - scopes[$delegate.$id] = $delegate; - watching[$delegate.$id] = {}; + /** + * ANGULAR HINT ALTERATION + * To make this loader compatible with apps that are running + * both Angular 1.2 and 1.3, the loader must handle 1.3 applications + * that expect to initialize their config blocks after all providers + * are registered. Hence, the configBlocks are added to the end + * of the exisiting invokeQueue. + */ + Object.defineProperty(moduleInstance, '_invokeQueue', { + get: function() { + return invokeQueue.concat(configBlocks); + } + }); - return $delegate; -} + if (configFn) { + config(configFn); + } -function decorateDollaCompile ($delegate) { - var newCompile = function () { - var link = $delegate.apply(this, arguments); + return moduleInstance; - return function (scope) { - var elt = link.apply(this, arguments); - var descriptor = scopeDescriptor(elt, scope); - hint.emit('scope:link', { - id: scope.$id, - descriptor: descriptor + /** + * @param {string} provider + * @param {string} method + * @param {String=} insertMethod + * @returns {angular.Module} + */ + function invokeLater(provider, method, insertMethod, queue) { + if (!queue) queue = invokeQueue; + return function() { + queue[insertMethod || 'push']([provider, method, arguments]); + return moduleInstance; + }; + } }); - return elt; }; - }; - - // TODO: test this - // copy private helpers like $$addScopeInfo - for (var prop in $delegate) { - if ($delegate.hasOwnProperty(prop)) { - newCompile[prop] = $delegate[prop]; - } - } - return newCompile; -} - -var TYPES = [ - 'ng-app', - 'ng-controller', - 'ng-repeat', - 'ng-include' -]; - -function scopeDescriptor (elt, scope) { - var val, - theseTypes = [], - type; + }); - if (elt) { - for (var i = 0, ii = TYPES.length; i < ii; i++) { - type = TYPES[i]; - if (val = elt.attr(type)) { - theseTypes.push(type + '="' + val + '"'); - } - } - } - if (theseTypes.length === 0) { - return 'scope.$id=' + scope.$id; - } else { - return theseTypes.join(' '); - } } -function byScopeId (scope) { - return scope.$id; -} +setupModuleLoader(window); +})(window); -function humanReadableWatchExpression (fn) { - if (fn.exp) { - fn = fn.exp; - } else if (fn.name) { - fn = fn.name; - } - return fn.toString(); -} +/** + * Closure compiler type information + * + * @typedef { { + * requires: !Array., + * invokeQueue: !Array.>, + * + * service: function(string, Function):angular.Module, + * factory: function(string, Function):angular.Module, + * value: function(string, *):angular.Module, + * + * filter: function(string, Function):angular.Module, + * + * init: function(Function):angular.Module + * } } + */ +angular.Module; -function isOneTimeBindExp(exp) { - // this is the same code angular 1.3.15 has to check - // for a one time bind expression - return exp.charAt(0) === ':' && exp.charAt(1) === ':'; -} -},{"../lib/summarize-model":9,"debounce-on":4}]},{},[1]); +},{}]},{},[28]); diff --git a/gulpfile.js b/gulpfile.js index 9b33672..51faa5d 100644 --- a/gulpfile.js +++ b/gulpfile.js @@ -24,6 +24,7 @@ gulp.task('package', ['browserify'], function () { './dist/**', './img/**', './panel/**', + 'libs/rx.all.js', 'background.js', 'devtoolsBackground.*', 'inject.js', diff --git a/libs/rx.all.js b/libs/rx.all.js new file mode 100644 index 0000000..42a42b1 --- /dev/null +++ b/libs/rx.all.js @@ -0,0 +1,10664 @@ +// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. + +;(function (undefined) { + + var objectTypes = { + 'boolean': false, + 'function': true, + 'object': true, + 'number': false, + 'string': false, + 'undefined': false + }; + + var root = (objectTypes[typeof window] && window) || this, + freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports, + freeModule = objectTypes[typeof module] && module && !module.nodeType && module, + moduleExports = freeModule && freeModule.exports === freeExports && freeExports, + freeGlobal = objectTypes[typeof global] && global; + + if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal)) { + root = freeGlobal; + } + + var Rx = { + internals: {}, + config: { + Promise: root.Promise + }, + helpers: { } + }; + + // Defaults + var noop = Rx.helpers.noop = function () { }, + notDefined = Rx.helpers.notDefined = function (x) { return typeof x === 'undefined'; }, + identity = Rx.helpers.identity = function (x) { return x; }, + pluck = Rx.helpers.pluck = function (property) { return function (x) { return x[property]; }; }, + just = Rx.helpers.just = function (value) { return function () { return value; }; }, + defaultNow = Rx.helpers.defaultNow = Date.now, + defaultComparer = Rx.helpers.defaultComparer = function (x, y) { return isEqual(x, y); }, + defaultSubComparer = Rx.helpers.defaultSubComparer = function (x, y) { return x > y ? 1 : (x < y ? -1 : 0); }, + defaultKeySerializer = Rx.helpers.defaultKeySerializer = function (x) { return x.toString(); }, + defaultError = Rx.helpers.defaultError = function (err) { throw err; }, + isPromise = Rx.helpers.isPromise = function (p) { return !!p && typeof p.subscribe !== 'function' && typeof p.then === 'function'; }, + asArray = Rx.helpers.asArray = function () { return Array.prototype.slice.call(arguments); }, + not = Rx.helpers.not = function (a) { return !a; }, + isFunction = Rx.helpers.isFunction = (function () { + + var isFn = function (value) { + return typeof value == 'function' || false; + } + + // fallback for older versions of Chrome and Safari + if (isFn(/x/)) { + isFn = function(value) { + return typeof value == 'function' && toString.call(value) == '[object Function]'; + }; + } + + return isFn; + }()); + + function cloneArray(arr) { for(var a = [], i = 0, len = arr.length; i < len; i++) { a.push(arr[i]); } return a;} + + Rx.config.longStackSupport = false; + var hasStacks = false; + try { + throw new Error(); + } catch (e) { + hasStacks = !!e.stack; + } + + // All code after this point will be filtered from stack traces reported by RxJS + var rStartingLine = captureLine(), rFileName; + + var STACK_JUMP_SEPARATOR = "From previous event:"; + + function makeStackTraceLong(error, observable) { + // If possible, transform the error stack trace by removing Node and RxJS + // cruft, then concatenating with the stack trace of `observable`. + if (hasStacks && + observable.stack && + typeof error === "object" && + error !== null && + error.stack && + error.stack.indexOf(STACK_JUMP_SEPARATOR) === -1 + ) { + var stacks = []; + for (var o = observable; !!o; o = o.source) { + if (o.stack) { + stacks.unshift(o.stack); + } + } + stacks.unshift(error.stack); + + var concatedStacks = stacks.join("\n" + STACK_JUMP_SEPARATOR + "\n"); + error.stack = filterStackString(concatedStacks); + } + } + + function filterStackString(stackString) { + var lines = stackString.split("\n"), + desiredLines = []; + for (var i = 0, len = lines.length; i < len; i++) { + var line = lines[i]; + + if (!isInternalFrame(line) && !isNodeFrame(line) && line) { + desiredLines.push(line); + } + } + return desiredLines.join("\n"); + } + + function isInternalFrame(stackLine) { + var fileNameAndLineNumber = getFileNameAndLineNumber(stackLine); + if (!fileNameAndLineNumber) { + return false; + } + var fileName = fileNameAndLineNumber[0], lineNumber = fileNameAndLineNumber[1]; + + return fileName === rFileName && + lineNumber >= rStartingLine && + lineNumber <= rEndingLine; + } + + function isNodeFrame(stackLine) { + return stackLine.indexOf("(module.js:") !== -1 || + stackLine.indexOf("(node.js:") !== -1; + } + + function captureLine() { + if (!hasStacks) { return; } + + try { + throw new Error(); + } catch (e) { + var lines = e.stack.split("\n"); + var firstLine = lines[0].indexOf("@") > 0 ? lines[1] : lines[2]; + var fileNameAndLineNumber = getFileNameAndLineNumber(firstLine); + if (!fileNameAndLineNumber) { return; } + + rFileName = fileNameAndLineNumber[0]; + return fileNameAndLineNumber[1]; + } + } + + function getFileNameAndLineNumber(stackLine) { + // Named functions: "at functionName (filename:lineNumber:columnNumber)" + var attempt1 = /at .+ \((.+):(\d+):(?:\d+)\)$/.exec(stackLine); + if (attempt1) { return [attempt1[1], Number(attempt1[2])]; } + + // Anonymous functions: "at filename:lineNumber:columnNumber" + var attempt2 = /at ([^ ]+):(\d+):(?:\d+)$/.exec(stackLine); + if (attempt2) { return [attempt2[1], Number(attempt2[2])]; } + + // Firefox style: "function@filename:lineNumber or @filename:lineNumber" + var attempt3 = /.*@(.+):(\d+)$/.exec(stackLine); + if (attempt3) { return [attempt3[1], Number(attempt3[2])]; } + } + + var EmptyError = Rx.EmptyError = function() { + this.message = 'Sequence contains no elements.'; + Error.call(this); + }; + EmptyError.prototype = Error.prototype; + + var ObjectDisposedError = Rx.ObjectDisposedError = function() { + this.message = 'Object has been disposed'; + Error.call(this); + }; + ObjectDisposedError.prototype = Error.prototype; + + var ArgumentOutOfRangeError = Rx.ArgumentOutOfRangeError = function () { + this.message = 'Argument out of range'; + Error.call(this); + }; + ArgumentOutOfRangeError.prototype = Error.prototype; + + var NotSupportedError = Rx.NotSupportedError = function (message) { + this.message = message || 'This operation is not supported'; + Error.call(this); + }; + NotSupportedError.prototype = Error.prototype; + + var NotImplementedError = Rx.NotImplementedError = function (message) { + this.message = message || 'This operation is not implemented'; + Error.call(this); + }; + NotImplementedError.prototype = Error.prototype; + + var notImplemented = Rx.helpers.notImplemented = function () { + throw new NotImplementedError(); + }; + + var notSupported = Rx.helpers.notSupported = function () { + throw new NotSupportedError(); + }; + + // Shim in iterator support + var $iterator$ = (typeof Symbol === 'function' && Symbol.iterator) || + '_es6shim_iterator_'; + // Bug for mozilla version + if (root.Set && typeof new root.Set()['@@iterator'] === 'function') { + $iterator$ = '@@iterator'; + } + + var doneEnumerator = Rx.doneEnumerator = { done: true, value: undefined }; + + var isIterable = Rx.helpers.isIterable = function (o) { + return o[$iterator$] !== undefined; + } + + var isArrayLike = Rx.helpers.isArrayLike = function (o) { + return o && o.length !== undefined; + } + + Rx.helpers.iterator = $iterator$; + + var bindCallback = Rx.internals.bindCallback = function (func, thisArg, argCount) { + if (typeof thisArg === 'undefined') { return func; } + switch(argCount) { + case 0: + return function() { + return func.call(thisArg) + }; + case 1: + return function(arg) { + return func.call(thisArg, arg); + } + case 2: + return function(value, index) { + return func.call(thisArg, value, index); + }; + case 3: + return function(value, index, collection) { + return func.call(thisArg, value, index, collection); + }; + } + + return function() { + return func.apply(thisArg, arguments); + }; + }; + + /** Used to determine if values are of the language type Object */ + var dontEnums = ['toString', + 'toLocaleString', + 'valueOf', + 'hasOwnProperty', + 'isPrototypeOf', + 'propertyIsEnumerable', + 'constructor'], + dontEnumsLength = dontEnums.length; + + /** `Object#toString` result shortcuts */ + var argsClass = '[object Arguments]', + arrayClass = '[object Array]', + boolClass = '[object Boolean]', + dateClass = '[object Date]', + errorClass = '[object Error]', + funcClass = '[object Function]', + numberClass = '[object Number]', + objectClass = '[object Object]', + regexpClass = '[object RegExp]', + stringClass = '[object String]'; + + var toString = Object.prototype.toString, + hasOwnProperty = Object.prototype.hasOwnProperty, + supportsArgsClass = toString.call(arguments) == argsClass, // For less -1); + } + }); + } + } + stackA.pop(); + stackB.pop(); + + return result; + } + + var hasProp = {}.hasOwnProperty, + slice = Array.prototype.slice; + + var inherits = this.inherits = Rx.internals.inherits = function (child, parent) { + function __() { this.constructor = child; } + __.prototype = parent.prototype; + child.prototype = new __(); + }; + + var addProperties = Rx.internals.addProperties = function (obj) { + for(var sources = [], i = 1, len = arguments.length; i < len; i++) { sources.push(arguments[i]); } + for (var idx = 0, ln = sources.length; idx < ln; idx++) { + var source = sources[idx]; + for (var prop in source) { + obj[prop] = source[prop]; + } + } + }; + + // Rx Utils + var addRef = Rx.internals.addRef = function (xs, r) { + return new AnonymousObservable(function (observer) { + return new CompositeDisposable(r.getDisposable(), xs.subscribe(observer)); + }); + }; + + function arrayInitialize(count, factory) { + var a = new Array(count); + for (var i = 0; i < count; i++) { + a[i] = factory(); + } + return a; + } + + var errorObj = {e: {}}; + var tryCatchTarget; + function tryCatcher() { + try { + return tryCatchTarget.apply(this, arguments); + } catch (e) { + errorObj.e = e; + return errorObj; + } + } + function tryCatch(fn) { + if (!isFunction(fn)) { throw new TypeError('fn must be a function'); } + tryCatchTarget = fn; + return tryCatcher; + } + function thrower(e) { + throw e; + } + + // Collections + function IndexedItem(id, value) { + this.id = id; + this.value = value; + } + + IndexedItem.prototype.compareTo = function (other) { + var c = this.value.compareTo(other.value); + c === 0 && (c = this.id - other.id); + return c; + }; + + // Priority Queue for Scheduling + var PriorityQueue = Rx.internals.PriorityQueue = function (capacity) { + this.items = new Array(capacity); + this.length = 0; + }; + + var priorityProto = PriorityQueue.prototype; + priorityProto.isHigherPriority = function (left, right) { + return this.items[left].compareTo(this.items[right]) < 0; + }; + + priorityProto.percolate = function (index) { + if (index >= this.length || index < 0) { return; } + var parent = index - 1 >> 1; + if (parent < 0 || parent === index) { return; } + if (this.isHigherPriority(index, parent)) { + var temp = this.items[index]; + this.items[index] = this.items[parent]; + this.items[parent] = temp; + this.percolate(parent); + } + }; + + priorityProto.heapify = function (index) { + +index || (index = 0); + if (index >= this.length || index < 0) { return; } + var left = 2 * index + 1, + right = 2 * index + 2, + first = index; + if (left < this.length && this.isHigherPriority(left, first)) { + first = left; + } + if (right < this.length && this.isHigherPriority(right, first)) { + first = right; + } + if (first !== index) { + var temp = this.items[index]; + this.items[index] = this.items[first]; + this.items[first] = temp; + this.heapify(first); + } + }; + + priorityProto.peek = function () { return this.items[0].value; }; + + priorityProto.removeAt = function (index) { + this.items[index] = this.items[--this.length]; + this.items[this.length] = undefined; + this.heapify(); + }; + + priorityProto.dequeue = function () { + var result = this.peek(); + this.removeAt(0); + return result; + }; + + priorityProto.enqueue = function (item) { + var index = this.length++; + this.items[index] = new IndexedItem(PriorityQueue.count++, item); + this.percolate(index); + }; + + priorityProto.remove = function (item) { + for (var i = 0; i < this.length; i++) { + if (this.items[i].value === item) { + this.removeAt(i); + return true; + } + } + return false; + }; + PriorityQueue.count = 0; + + /** + * Represents a group of disposable resources that are disposed together. + * @constructor + */ + var CompositeDisposable = Rx.CompositeDisposable = function () { + var args = [], i, len; + if (Array.isArray(arguments[0])) { + args = arguments[0]; + len = args.length; + } else { + len = arguments.length; + args = new Array(len); + for(i = 0; i < len; i++) { args[i] = arguments[i]; } + } + for(i = 0; i < len; i++) { + if (!isDisposable(args[i])) { throw new TypeError('Not a disposable'); } + } + this.disposables = args; + this.isDisposed = false; + this.length = args.length; + }; + + var CompositeDisposablePrototype = CompositeDisposable.prototype; + + /** + * Adds a disposable to the CompositeDisposable or disposes the disposable if the CompositeDisposable is disposed. + * @param {Mixed} item Disposable to add. + */ + CompositeDisposablePrototype.add = function (item) { + if (this.isDisposed) { + item.dispose(); + } else { + this.disposables.push(item); + this.length++; + } + }; + + /** + * Removes and disposes the first occurrence of a disposable from the CompositeDisposable. + * @param {Mixed} item Disposable to remove. + * @returns {Boolean} true if found; false otherwise. + */ + CompositeDisposablePrototype.remove = function (item) { + var shouldDispose = false; + if (!this.isDisposed) { + var idx = this.disposables.indexOf(item); + if (idx !== -1) { + shouldDispose = true; + this.disposables.splice(idx, 1); + this.length--; + item.dispose(); + } + } + return shouldDispose; + }; + + /** + * Disposes all disposables in the group and removes them from the group. + */ + CompositeDisposablePrototype.dispose = function () { + if (!this.isDisposed) { + this.isDisposed = true; + var len = this.disposables.length, currentDisposables = new Array(len); + for(var i = 0; i < len; i++) { currentDisposables[i] = this.disposables[i]; } + this.disposables = []; + this.length = 0; + + for (i = 0; i < len; i++) { + currentDisposables[i].dispose(); + } + } + }; + + /** + * Provides a set of static methods for creating Disposables. + * @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once. + */ + var Disposable = Rx.Disposable = function (action) { + this.isDisposed = false; + this.action = action || noop; + }; + + /** Performs the task of cleaning up resources. */ + Disposable.prototype.dispose = function () { + if (!this.isDisposed) { + this.action(); + this.isDisposed = true; + } + }; + + /** + * Creates a disposable object that invokes the specified action when disposed. + * @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once. + * @return {Disposable} The disposable object that runs the given action upon disposal. + */ + var disposableCreate = Disposable.create = function (action) { return new Disposable(action); }; + + /** + * Gets the disposable that does nothing when disposed. + */ + var disposableEmpty = Disposable.empty = { dispose: noop }; + + /** + * Validates whether the given object is a disposable + * @param {Object} Object to test whether it has a dispose method + * @returns {Boolean} true if a disposable object, else false. + */ + var isDisposable = Disposable.isDisposable = function (d) { + return d && isFunction(d.dispose); + }; + + var checkDisposed = Disposable.checkDisposed = function (disposable) { + if (disposable.isDisposed) { throw new ObjectDisposedError(); } + }; + + // Single assignment + var SingleAssignmentDisposable = Rx.SingleAssignmentDisposable = function () { + this.isDisposed = false; + this.current = null; + }; + SingleAssignmentDisposable.prototype.getDisposable = function () { + return this.current; + }; + SingleAssignmentDisposable.prototype.setDisposable = function (value) { + if (this.current) { throw new Error('Disposable has already been assigned'); } + var shouldDispose = this.isDisposed; + !shouldDispose && (this.current = value); + shouldDispose && value && value.dispose(); + }; + SingleAssignmentDisposable.prototype.dispose = function () { + if (!this.isDisposed) { + this.isDisposed = true; + var old = this.current; + this.current = null; + } + old && old.dispose(); + }; + + // Multiple assignment disposable + var SerialDisposable = Rx.SerialDisposable = function () { + this.isDisposed = false; + this.current = null; + }; + SerialDisposable.prototype.getDisposable = function () { + return this.current; + }; + SerialDisposable.prototype.setDisposable = function (value) { + var shouldDispose = this.isDisposed; + if (!shouldDispose) { + var old = this.current; + this.current = value; + } + old && old.dispose(); + shouldDispose && value && value.dispose(); + }; + SerialDisposable.prototype.dispose = function () { + if (!this.isDisposed) { + this.isDisposed = true; + var old = this.current; + this.current = null; + } + old && old.dispose(); + }; + + /** + * Represents a disposable resource that only disposes its underlying disposable resource when all dependent disposable objects have been disposed. + */ + var RefCountDisposable = Rx.RefCountDisposable = (function () { + + function InnerDisposable(disposable) { + this.disposable = disposable; + this.disposable.count++; + this.isInnerDisposed = false; + } + + InnerDisposable.prototype.dispose = function () { + if (!this.disposable.isDisposed && !this.isInnerDisposed) { + this.isInnerDisposed = true; + this.disposable.count--; + if (this.disposable.count === 0 && this.disposable.isPrimaryDisposed) { + this.disposable.isDisposed = true; + this.disposable.underlyingDisposable.dispose(); + } + } + }; + + /** + * Initializes a new instance of the RefCountDisposable with the specified disposable. + * @constructor + * @param {Disposable} disposable Underlying disposable. + */ + function RefCountDisposable(disposable) { + this.underlyingDisposable = disposable; + this.isDisposed = false; + this.isPrimaryDisposed = false; + this.count = 0; + } + + /** + * Disposes the underlying disposable only when all dependent disposables have been disposed + */ + RefCountDisposable.prototype.dispose = function () { + if (!this.isDisposed && !this.isPrimaryDisposed) { + this.isPrimaryDisposed = true; + if (this.count === 0) { + this.isDisposed = true; + this.underlyingDisposable.dispose(); + } + } + }; + + /** + * Returns a dependent disposable that when disposed decreases the refcount on the underlying disposable. + * @returns {Disposable} A dependent disposable contributing to the reference count that manages the underlying disposable's lifetime. + */ + RefCountDisposable.prototype.getDisposable = function () { + return this.isDisposed ? disposableEmpty : new InnerDisposable(this); + }; + + return RefCountDisposable; + })(); + + function ScheduledDisposable(scheduler, disposable) { + this.scheduler = scheduler; + this.disposable = disposable; + this.isDisposed = false; + } + + function scheduleItem(s, self) { + if (!self.isDisposed) { + self.isDisposed = true; + self.disposable.dispose(); + } + } + + ScheduledDisposable.prototype.dispose = function () { + this.scheduler.scheduleWithState(this, scheduleItem); + }; + + var ScheduledItem = Rx.internals.ScheduledItem = function (scheduler, state, action, dueTime, comparer) { + this.scheduler = scheduler; + this.state = state; + this.action = action; + this.dueTime = dueTime; + this.comparer = comparer || defaultSubComparer; + this.disposable = new SingleAssignmentDisposable(); + } + + ScheduledItem.prototype.invoke = function () { + this.disposable.setDisposable(this.invokeCore()); + }; + + ScheduledItem.prototype.compareTo = function (other) { + return this.comparer(this.dueTime, other.dueTime); + }; + + ScheduledItem.prototype.isCancelled = function () { + return this.disposable.isDisposed; + }; + + ScheduledItem.prototype.invokeCore = function () { + return this.action(this.scheduler, this.state); + }; + + /** Provides a set of static properties to access commonly used schedulers. */ + var Scheduler = Rx.Scheduler = (function () { + + function Scheduler(now, schedule, scheduleRelative, scheduleAbsolute) { + this.now = now; + this._schedule = schedule; + this._scheduleRelative = scheduleRelative; + this._scheduleAbsolute = scheduleAbsolute; + } + + /** Determines whether the given object is a scheduler */ + Scheduler.isScheduler = function (s) { + return s instanceof Scheduler; + } + + function invokeAction(scheduler, action) { + action(); + return disposableEmpty; + } + + var schedulerProto = Scheduler.prototype; + + /** + * Schedules an action to be executed. + * @param {Function} action Action to execute. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.schedule = function (action) { + return this._schedule(action, invokeAction); + }; + + /** + * Schedules an action to be executed. + * @param state State passed to the action to be executed. + * @param {Function} action Action to be executed. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleWithState = function (state, action) { + return this._schedule(state, action); + }; + + /** + * Schedules an action to be executed after the specified relative due time. + * @param {Function} action Action to execute. + * @param {Number} dueTime Relative time after which to execute the action. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleWithRelative = function (dueTime, action) { + return this._scheduleRelative(action, dueTime, invokeAction); + }; + + /** + * Schedules an action to be executed after dueTime. + * @param state State passed to the action to be executed. + * @param {Function} action Action to be executed. + * @param {Number} dueTime Relative time after which to execute the action. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleWithRelativeAndState = function (state, dueTime, action) { + return this._scheduleRelative(state, dueTime, action); + }; + + /** + * Schedules an action to be executed at the specified absolute due time. + * @param {Function} action Action to execute. + * @param {Number} dueTime Absolute time at which to execute the action. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleWithAbsolute = function (dueTime, action) { + return this._scheduleAbsolute(action, dueTime, invokeAction); + }; + + /** + * Schedules an action to be executed at dueTime. + * @param {Mixed} state State passed to the action to be executed. + * @param {Function} action Action to be executed. + * @param {Number}dueTime Absolute time at which to execute the action. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleWithAbsoluteAndState = function (state, dueTime, action) { + return this._scheduleAbsolute(state, dueTime, action); + }; + + /** Gets the current time according to the local machine's system clock. */ + Scheduler.now = defaultNow; + + /** + * Normalizes the specified TimeSpan value to a positive value. + * @param {Number} timeSpan The time span value to normalize. + * @returns {Number} The specified TimeSpan value if it is zero or positive; otherwise, 0 + */ + Scheduler.normalize = function (timeSpan) { + timeSpan < 0 && (timeSpan = 0); + return timeSpan; + }; + + return Scheduler; + }()); + + var normalizeTime = Scheduler.normalize, isScheduler = Scheduler.isScheduler; + + (function (schedulerProto) { + + function invokeRecImmediate(scheduler, pair) { + var state = pair[0], action = pair[1], group = new CompositeDisposable(); + + function recursiveAction(state1) { + action(state1, function (state2) { + var isAdded = false, isDone = false, + d = scheduler.scheduleWithState(state2, function (scheduler1, state3) { + if (isAdded) { + group.remove(d); + } else { + isDone = true; + } + recursiveAction(state3); + return disposableEmpty; + }); + if (!isDone) { + group.add(d); + isAdded = true; + } + }); + } + recursiveAction(state); + return group; + } + + function invokeRecDate(scheduler, pair, method) { + var state = pair[0], action = pair[1], group = new CompositeDisposable(); + function recursiveAction(state1) { + action(state1, function (state2, dueTime1) { + var isAdded = false, isDone = false, + d = scheduler[method](state2, dueTime1, function (scheduler1, state3) { + if (isAdded) { + group.remove(d); + } else { + isDone = true; + } + recursiveAction(state3); + return disposableEmpty; + }); + if (!isDone) { + group.add(d); + isAdded = true; + } + }); + }; + recursiveAction(state); + return group; + } + + function scheduleInnerRecursive(action, self) { + action(function(dt) { self(action, dt); }); + } + + /** + * Schedules an action to be executed recursively. + * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleRecursive = function (action) { + return this.scheduleRecursiveWithState(action, scheduleInnerRecursive); + }; + + /** + * Schedules an action to be executed recursively. + * @param {Mixed} state State passed to the action to be executed. + * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in recursive invocation state. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleRecursiveWithState = function (state, action) { + return this.scheduleWithState([state, action], invokeRecImmediate); + }; + + /** + * Schedules an action to be executed recursively after a specified relative due time. + * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified relative time. + * @param {Number}dueTime Relative time after which to execute the action for the first time. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleRecursiveWithRelative = function (dueTime, action) { + return this.scheduleRecursiveWithRelativeAndState(action, dueTime, scheduleInnerRecursive); + }; + + /** + * Schedules an action to be executed recursively after a specified relative due time. + * @param {Mixed} state State passed to the action to be executed. + * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state. + * @param {Number}dueTime Relative time after which to execute the action for the first time. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleRecursiveWithRelativeAndState = function (state, dueTime, action) { + return this._scheduleRelative([state, action], dueTime, function (s, p) { + return invokeRecDate(s, p, 'scheduleWithRelativeAndState'); + }); + }; + + /** + * Schedules an action to be executed recursively at a specified absolute due time. + * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified absolute time. + * @param {Number}dueTime Absolute time at which to execute the action for the first time. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleRecursiveWithAbsolute = function (dueTime, action) { + return this.scheduleRecursiveWithAbsoluteAndState(action, dueTime, scheduleInnerRecursive); + }; + + /** + * Schedules an action to be executed recursively at a specified absolute due time. + * @param {Mixed} state State passed to the action to be executed. + * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state. + * @param {Number}dueTime Absolute time at which to execute the action for the first time. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleRecursiveWithAbsoluteAndState = function (state, dueTime, action) { + return this._scheduleAbsolute([state, action], dueTime, function (s, p) { + return invokeRecDate(s, p, 'scheduleWithAbsoluteAndState'); + }); + }; + }(Scheduler.prototype)); + + (function (schedulerProto) { + + /** + * Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation. + * @param {Number} period Period for running the work periodically. + * @param {Function} action Action to be executed. + * @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort). + */ + Scheduler.prototype.schedulePeriodic = function (period, action) { + return this.schedulePeriodicWithState(null, period, action); + }; + + /** + * Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation. + * @param {Mixed} state Initial state passed to the action upon the first iteration. + * @param {Number} period Period for running the work periodically. + * @param {Function} action Action to be executed, potentially updating the state. + * @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort). + */ + Scheduler.prototype.schedulePeriodicWithState = function(state, period, action) { + if (typeof root.setInterval === 'undefined') { throw new NotSupportedError(); } + period = normalizeTime(period); + var s = state, id = root.setInterval(function () { s = action(s); }, period); + return disposableCreate(function () { root.clearInterval(id); }); + }; + + }(Scheduler.prototype)); + + (function (schedulerProto) { + /** + * Returns a scheduler that wraps the original scheduler, adding exception handling for scheduled actions. + * @param {Function} handler Handler that's run if an exception is caught. The exception will be rethrown if the handler returns false. + * @returns {Scheduler} Wrapper around the original scheduler, enforcing exception handling. + */ + schedulerProto.catchError = schedulerProto['catch'] = function (handler) { + return new CatchScheduler(this, handler); + }; + }(Scheduler.prototype)); + + var SchedulePeriodicRecursive = Rx.internals.SchedulePeriodicRecursive = (function () { + function tick(command, recurse) { + recurse(0, this._period); + try { + this._state = this._action(this._state); + } catch (e) { + this._cancel.dispose(); + throw e; + } + } + + function SchedulePeriodicRecursive(scheduler, state, period, action) { + this._scheduler = scheduler; + this._state = state; + this._period = period; + this._action = action; + } + + SchedulePeriodicRecursive.prototype.start = function () { + var d = new SingleAssignmentDisposable(); + this._cancel = d; + d.setDisposable(this._scheduler.scheduleRecursiveWithRelativeAndState(0, this._period, tick.bind(this))); + + return d; + }; + + return SchedulePeriodicRecursive; + }()); + + /** Gets a scheduler that schedules work immediately on the current thread. */ + var immediateScheduler = Scheduler.immediate = (function () { + function scheduleNow(state, action) { return action(this, state); } + return new Scheduler(defaultNow, scheduleNow, notSupported, notSupported); + }()); + + /** + * Gets a scheduler that schedules work as soon as possible on the current thread. + */ + var currentThreadScheduler = Scheduler.currentThread = (function () { + var queue; + + function runTrampoline () { + while (queue.length > 0) { + var item = queue.shift(); + !item.isCancelled() && item.invoke(); + } + } + + function scheduleNow(state, action) { + var si = new ScheduledItem(this, state, action, this.now()); + + if (!queue) { + queue = [si]; + + var result = tryCatch(runTrampoline)(); + queue = null; + if (result === errorObj) { return thrower(result.e); } + } else { + queue.push(si); + } + return si.disposable; + } + + var currentScheduler = new Scheduler(defaultNow, scheduleNow, notSupported, notSupported); + currentScheduler.scheduleRequired = function () { return !queue; }; + + return currentScheduler; + }()); + + var scheduleMethod, clearMethod; + + var localTimer = (function () { + var localSetTimeout, localClearTimeout = noop; + if (!!root.setTimeout) { + localSetTimeout = root.setTimeout; + localClearTimeout = root.clearTimeout; + } else if (!!root.WScript) { + localSetTimeout = function (fn, time) { + root.WScript.Sleep(time); + fn(); + }; + } else { + throw new NotSupportedError(); + } + + return { + setTimeout: localSetTimeout, + clearTimeout: localClearTimeout + }; + }()); + var localSetTimeout = localTimer.setTimeout, + localClearTimeout = localTimer.clearTimeout; + + (function () { + + var nextHandle = 1, tasksByHandle = {}, currentlyRunning = false; + + clearMethod = function (handle) { + delete tasksByHandle[handle]; + }; + + function runTask(handle) { + if (currentlyRunning) { + localSetTimeout(function () { runTask(handle) }, 0); + } else { + var task = tasksByHandle[handle]; + if (task) { + currentlyRunning = true; + var result = tryCatch(task)(); + clearMethod(handle); + currentlyRunning = false; + if (result === errorObj) { return thrower(result.e); } + } + } + } + + var reNative = RegExp('^' + + String(toString) + .replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + .replace(/toString| for [^\]]+/g, '.*?') + '$' + ); + + var setImmediate = typeof (setImmediate = freeGlobal && moduleExports && freeGlobal.setImmediate) == 'function' && + !reNative.test(setImmediate) && setImmediate; + + function postMessageSupported () { + // Ensure not in a worker + if (!root.postMessage || root.importScripts) { return false; } + var isAsync = false, oldHandler = root.onmessage; + // Test for async + root.onmessage = function () { isAsync = true; }; + root.postMessage('', '*'); + root.onmessage = oldHandler; + + return isAsync; + } + + // Use in order, setImmediate, nextTick, postMessage, MessageChannel, script readystatechanged, setTimeout + if (isFunction(setImmediate)) { + scheduleMethod = function (action) { + var id = nextHandle++; + tasksByHandle[id] = action; + setImmediate(function () { runTask(id); }); + + return id; + }; + } else if (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]') { + scheduleMethod = function (action) { + var id = nextHandle++; + tasksByHandle[id] = action; + process.nextTick(function () { runTask(id); }); + + return id; + }; + } else if (postMessageSupported()) { + var MSG_PREFIX = 'ms.rx.schedule' + Math.random(); + + function onGlobalPostMessage(event) { + // Only if we're a match to avoid any other global events + if (typeof event.data === 'string' && event.data.substring(0, MSG_PREFIX.length) === MSG_PREFIX) { + runTask(event.data.substring(MSG_PREFIX.length)); + } + } + + if (root.addEventListener) { + root.addEventListener('message', onGlobalPostMessage, false); + } else if (root.attachEvent) { + root.attachEvent('onmessage', onGlobalPostMessage); + } else { + root.onmessage = onGlobalPostMessage; + } + + scheduleMethod = function (action) { + var id = nextHandle++; + tasksByHandle[id] = action; + root.postMessage(MSG_PREFIX + currentId, '*'); + return id; + }; + } else if (!!root.MessageChannel) { + var channel = new root.MessageChannel(); + + channel.port1.onmessage = function (e) { runTask(e.data); }; + + scheduleMethod = function (action) { + var id = nextHandle++; + tasksByHandle[id] = action; + channel.port2.postMessage(id); + return id; + }; + } else if ('document' in root && 'onreadystatechange' in root.document.createElement('script')) { + + scheduleMethod = function (action) { + var scriptElement = root.document.createElement('script'); + var id = nextHandle++; + tasksByHandle[id] = action; + + scriptElement.onreadystatechange = function () { + runTask(id); + scriptElement.onreadystatechange = null; + scriptElement.parentNode.removeChild(scriptElement); + scriptElement = null; + }; + root.document.documentElement.appendChild(scriptElement); + return id; + }; + + } else { + scheduleMethod = function (action) { + var id = nextHandle++; + tasksByHandle[id] = action; + localSetTimeout(function () { + runTask(id); + }, 0); + + return id; + }; + } + }()); + + /** + * Gets a scheduler that schedules work via a timed callback based upon platform. + */ + var timeoutScheduler = Scheduler.timeout = Scheduler['default'] = (function () { + + function scheduleNow(state, action) { + var scheduler = this, disposable = new SingleAssignmentDisposable(); + var id = scheduleMethod(function () { + !disposable.isDisposed && disposable.setDisposable(action(scheduler, state)); + }); + return new CompositeDisposable(disposable, disposableCreate(function () { + clearMethod(id); + })); + } + + function scheduleRelative(state, dueTime, action) { + var scheduler = this, dt = Scheduler.normalize(dueTime), disposable = new SingleAssignmentDisposable(); + if (dt === 0) { return scheduler.scheduleWithState(state, action); } + var id = localSetTimeout(function () { + !disposable.isDisposed && disposable.setDisposable(action(scheduler, state)); + }, dt); + return new CompositeDisposable(disposable, disposableCreate(function () { + localClearTimeout(id); + })); + } + + function scheduleAbsolute(state, dueTime, action) { + return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); + } + + return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); + })(); + + var CatchScheduler = (function (__super__) { + + function scheduleNow(state, action) { + return this._scheduler.scheduleWithState(state, this._wrap(action)); + } + + function scheduleRelative(state, dueTime, action) { + return this._scheduler.scheduleWithRelativeAndState(state, dueTime, this._wrap(action)); + } + + function scheduleAbsolute(state, dueTime, action) { + return this._scheduler.scheduleWithAbsoluteAndState(state, dueTime, this._wrap(action)); + } + + inherits(CatchScheduler, __super__); + + function CatchScheduler(scheduler, handler) { + this._scheduler = scheduler; + this._handler = handler; + this._recursiveOriginal = null; + this._recursiveWrapper = null; + __super__.call(this, this._scheduler.now.bind(this._scheduler), scheduleNow, scheduleRelative, scheduleAbsolute); + } + + CatchScheduler.prototype._clone = function (scheduler) { + return new CatchScheduler(scheduler, this._handler); + }; + + CatchScheduler.prototype._wrap = function (action) { + var parent = this; + return function (self, state) { + try { + return action(parent._getRecursiveWrapper(self), state); + } catch (e) { + if (!parent._handler(e)) { throw e; } + return disposableEmpty; + } + }; + }; + + CatchScheduler.prototype._getRecursiveWrapper = function (scheduler) { + if (this._recursiveOriginal !== scheduler) { + this._recursiveOriginal = scheduler; + var wrapper = this._clone(scheduler); + wrapper._recursiveOriginal = scheduler; + wrapper._recursiveWrapper = wrapper; + this._recursiveWrapper = wrapper; + } + return this._recursiveWrapper; + }; + + CatchScheduler.prototype.schedulePeriodicWithState = function (state, period, action) { + var self = this, failed = false, d = new SingleAssignmentDisposable(); + + d.setDisposable(this._scheduler.schedulePeriodicWithState(state, period, function (state1) { + if (failed) { return null; } + try { + return action(state1); + } catch (e) { + failed = true; + if (!self._handler(e)) { throw e; } + d.dispose(); + return null; + } + })); + + return d; + }; + + return CatchScheduler; + }(Scheduler)); + + /** + * Represents a notification to an observer. + */ + var Notification = Rx.Notification = (function () { + function Notification(kind, value, exception, accept, acceptObservable, toString) { + this.kind = kind; + this.value = value; + this.exception = exception; + this._accept = accept; + this._acceptObservable = acceptObservable; + this.toString = toString; + } + + /** + * Invokes the delegate corresponding to the notification or the observer's method corresponding to the notification and returns the produced result. + * + * @memberOf Notification + * @param {Any} observerOrOnNext Delegate to invoke for an OnNext notification or Observer to invoke the notification on.. + * @param {Function} onError Delegate to invoke for an OnError notification. + * @param {Function} onCompleted Delegate to invoke for an OnCompleted notification. + * @returns {Any} Result produced by the observation. + */ + Notification.prototype.accept = function (observerOrOnNext, onError, onCompleted) { + return observerOrOnNext && typeof observerOrOnNext === 'object' ? + this._acceptObservable(observerOrOnNext) : + this._accept(observerOrOnNext, onError, onCompleted); + }; + + /** + * Returns an observable sequence with a single notification. + * + * @memberOf Notifications + * @param {Scheduler} [scheduler] Scheduler to send out the notification calls on. + * @returns {Observable} The observable sequence that surfaces the behavior of the notification upon subscription. + */ + Notification.prototype.toObservable = function (scheduler) { + var self = this; + isScheduler(scheduler) || (scheduler = immediateScheduler); + return new AnonymousObservable(function (observer) { + return scheduler.scheduleWithState(self, function (_, notification) { + notification._acceptObservable(observer); + notification.kind === 'N' && observer.onCompleted(); + }); + }); + }; + + return Notification; + })(); + + /** + * Creates an object that represents an OnNext notification to an observer. + * @param {Any} value The value contained in the notification. + * @returns {Notification} The OnNext notification containing the value. + */ + var notificationCreateOnNext = Notification.createOnNext = (function () { + function _accept(onNext) { return onNext(this.value); } + function _acceptObservable(observer) { return observer.onNext(this.value); } + function toString() { return 'OnNext(' + this.value + ')'; } + + return function (value) { + return new Notification('N', value, null, _accept, _acceptObservable, toString); + }; + }()); + + /** + * Creates an object that represents an OnError notification to an observer. + * @param {Any} error The exception contained in the notification. + * @returns {Notification} The OnError notification containing the exception. + */ + var notificationCreateOnError = Notification.createOnError = (function () { + function _accept (onNext, onError) { return onError(this.exception); } + function _acceptObservable(observer) { return observer.onError(this.exception); } + function toString () { return 'OnError(' + this.exception + ')'; } + + return function (e) { + return new Notification('E', null, e, _accept, _acceptObservable, toString); + }; + }()); + + /** + * Creates an object that represents an OnCompleted notification to an observer. + * @returns {Notification} The OnCompleted notification. + */ + var notificationCreateOnCompleted = Notification.createOnCompleted = (function () { + function _accept (onNext, onError, onCompleted) { return onCompleted(); } + function _acceptObservable(observer) { return observer.onCompleted(); } + function toString () { return 'OnCompleted()'; } + + return function () { + return new Notification('C', null, null, _accept, _acceptObservable, toString); + }; + }()); + + /** + * Supports push-style iteration over an observable sequence. + */ + var Observer = Rx.Observer = function () { }; + + /** + * Creates a notification callback from an observer. + * @returns The action that forwards its input notification to the underlying observer. + */ + Observer.prototype.toNotifier = function () { + var observer = this; + return function (n) { return n.accept(observer); }; + }; + + /** + * Hides the identity of an observer. + * @returns An observer that hides the identity of the specified observer. + */ + Observer.prototype.asObserver = function () { + var self = this; + return new AnonymousObserver( + function (x) { self.onNext(x); }, + function (err) { self.onError(err); }, + function () { self.onCompleted(); }); + }; + + /** + * Checks access to the observer for grammar violations. This includes checking for multiple OnError or OnCompleted calls, as well as reentrancy in any of the observer methods. + * If a violation is detected, an Error is thrown from the offending observer method call. + * @returns An observer that checks callbacks invocations against the observer grammar and, if the checks pass, forwards those to the specified observer. + */ + Observer.prototype.checked = function () { return new CheckedObserver(this); }; + + /** + * Creates an observer from the specified OnNext, along with optional OnError, and OnCompleted actions. + * @param {Function} [onNext] Observer's OnNext action implementation. + * @param {Function} [onError] Observer's OnError action implementation. + * @param {Function} [onCompleted] Observer's OnCompleted action implementation. + * @returns {Observer} The observer object implemented using the given actions. + */ + var observerCreate = Observer.create = function (onNext, onError, onCompleted) { + onNext || (onNext = noop); + onError || (onError = defaultError); + onCompleted || (onCompleted = noop); + return new AnonymousObserver(onNext, onError, onCompleted); + }; + + /** + * Creates an observer from a notification callback. + * + * @static + * @memberOf Observer + * @param {Function} handler Action that handles a notification. + * @returns The observer object that invokes the specified handler using a notification corresponding to each message it receives. + */ + Observer.fromNotifier = function (handler, thisArg) { + var cb = bindCallback(handler, thisArg, 1); + return new AnonymousObserver(function (x) { + return cb(notificationCreateOnNext(x)); + }, function (e) { + return cb(notificationCreateOnError(e)); + }, function () { + return cb(notificationCreateOnCompleted()); + }); + }; + + /** + * Schedules the invocation of observer methods on the given scheduler. + * @param {Scheduler} scheduler Scheduler to schedule observer messages on. + * @returns {Observer} Observer whose messages are scheduled on the given scheduler. + */ + Observer.prototype.notifyOn = function (scheduler) { + return new ObserveOnObserver(scheduler, this); + }; + + Observer.prototype.makeSafe = function(disposable) { + return new AnonymousSafeObserver(this._onNext, this._onError, this._onCompleted, disposable); + }; + + /** + * Abstract base class for implementations of the Observer class. + * This base class enforces the grammar of observers where OnError and OnCompleted are terminal messages. + */ + var AbstractObserver = Rx.internals.AbstractObserver = (function (__super__) { + inherits(AbstractObserver, __super__); + + /** + * Creates a new observer in a non-stopped state. + */ + function AbstractObserver() { + this.isStopped = false; + __super__.call(this); + } + + // Must be implemented by other observers + AbstractObserver.prototype.next = notImplemented; + AbstractObserver.prototype.error = notImplemented; + AbstractObserver.prototype.completed = notImplemented; + + /** + * Notifies the observer of a new element in the sequence. + * @param {Any} value Next element in the sequence. + */ + AbstractObserver.prototype.onNext = function (value) { + if (!this.isStopped) { this.next(value); } + }; + + /** + * Notifies the observer that an exception has occurred. + * @param {Any} error The error that has occurred. + */ + AbstractObserver.prototype.onError = function (error) { + if (!this.isStopped) { + this.isStopped = true; + this.error(error); + } + }; + + /** + * Notifies the observer of the end of the sequence. + */ + AbstractObserver.prototype.onCompleted = function () { + if (!this.isStopped) { + this.isStopped = true; + this.completed(); + } + }; + + /** + * Disposes the observer, causing it to transition to the stopped state. + */ + AbstractObserver.prototype.dispose = function () { + this.isStopped = true; + }; + + AbstractObserver.prototype.fail = function (e) { + if (!this.isStopped) { + this.isStopped = true; + this.error(e); + return true; + } + + return false; + }; + + return AbstractObserver; + }(Observer)); + + /** + * Class to create an Observer instance from delegate-based implementations of the on* methods. + */ + var AnonymousObserver = Rx.AnonymousObserver = (function (__super__) { + inherits(AnonymousObserver, __super__); + + /** + * Creates an observer from the specified OnNext, OnError, and OnCompleted actions. + * @param {Any} onNext Observer's OnNext action implementation. + * @param {Any} onError Observer's OnError action implementation. + * @param {Any} onCompleted Observer's OnCompleted action implementation. + */ + function AnonymousObserver(onNext, onError, onCompleted) { + __super__.call(this); + this._onNext = onNext; + this._onError = onError; + this._onCompleted = onCompleted; + } + + /** + * Calls the onNext action. + * @param {Any} value Next element in the sequence. + */ + AnonymousObserver.prototype.next = function (value) { + this._onNext(value); + }; + + /** + * Calls the onError action. + * @param {Any} error The error that has occurred. + */ + AnonymousObserver.prototype.error = function (error) { + this._onError(error); + }; + + /** + * Calls the onCompleted action. + */ + AnonymousObserver.prototype.completed = function () { + this._onCompleted(); + }; + + return AnonymousObserver; + }(AbstractObserver)); + + var CheckedObserver = (function (__super__) { + inherits(CheckedObserver, __super__); + + function CheckedObserver(observer) { + __super__.call(this); + this._observer = observer; + this._state = 0; // 0 - idle, 1 - busy, 2 - done + } + + var CheckedObserverPrototype = CheckedObserver.prototype; + + CheckedObserverPrototype.onNext = function (value) { + this.checkAccess(); + var res = tryCatch(this._observer.onNext).call(this._observer, value); + this._state = 0; + res === errorObj && thrower(res.e); + }; + + CheckedObserverPrototype.onError = function (err) { + this.checkAccess(); + var res = tryCatch(this._observer.onError).call(this._observer, err); + this._state = 2; + res === errorObj && thrower(res.e); + }; + + CheckedObserverPrototype.onCompleted = function () { + this.checkAccess(); + var res = tryCatch(this._observer.onCompleted).call(this._observer); + this._state = 2; + res === errorObj && thrower(res.e); + }; + + CheckedObserverPrototype.checkAccess = function () { + if (this._state === 1) { throw new Error('Re-entrancy detected'); } + if (this._state === 2) { throw new Error('Observer completed'); } + if (this._state === 0) { this._state = 1; } + }; + + return CheckedObserver; + }(Observer)); + + var ScheduledObserver = Rx.internals.ScheduledObserver = (function (__super__) { + inherits(ScheduledObserver, __super__); + + function ScheduledObserver(scheduler, observer) { + __super__.call(this); + this.scheduler = scheduler; + this.observer = observer; + this.isAcquired = false; + this.hasFaulted = false; + this.queue = []; + this.disposable = new SerialDisposable(); + } + + ScheduledObserver.prototype.next = function (value) { + var self = this; + this.queue.push(function () { self.observer.onNext(value); }); + }; + + ScheduledObserver.prototype.error = function (e) { + var self = this; + this.queue.push(function () { self.observer.onError(e); }); + }; + + ScheduledObserver.prototype.completed = function () { + var self = this; + this.queue.push(function () { self.observer.onCompleted(); }); + }; + + ScheduledObserver.prototype.ensureActive = function () { + var isOwner = false, parent = this; + if (!this.hasFaulted && this.queue.length > 0) { + isOwner = !this.isAcquired; + this.isAcquired = true; + } + if (isOwner) { + this.disposable.setDisposable(this.scheduler.scheduleRecursive(function (self) { + var work; + if (parent.queue.length > 0) { + work = parent.queue.shift(); + } else { + parent.isAcquired = false; + return; + } + try { + work(); + } catch (ex) { + parent.queue = []; + parent.hasFaulted = true; + throw ex; + } + self(); + })); + } + }; + + ScheduledObserver.prototype.dispose = function () { + __super__.prototype.dispose.call(this); + this.disposable.dispose(); + }; + + return ScheduledObserver; + }(AbstractObserver)); + + var ObserveOnObserver = (function (__super__) { + inherits(ObserveOnObserver, __super__); + + function ObserveOnObserver(scheduler, observer, cancel) { + __super__.call(this, scheduler, observer); + this._cancel = cancel; + } + + ObserveOnObserver.prototype.next = function (value) { + __super__.prototype.next.call(this, value); + this.ensureActive(); + }; + + ObserveOnObserver.prototype.error = function (e) { + __super__.prototype.error.call(this, e); + this.ensureActive(); + }; + + ObserveOnObserver.prototype.completed = function () { + __super__.prototype.completed.call(this); + this.ensureActive(); + }; + + ObserveOnObserver.prototype.dispose = function () { + __super__.prototype.dispose.call(this); + this._cancel && this._cancel.dispose(); + this._cancel = null; + }; + + return ObserveOnObserver; + })(ScheduledObserver); + + var observableProto; + + /** + * Represents a push-style collection. + */ + var Observable = Rx.Observable = (function () { + + function Observable(subscribe) { + if (Rx.config.longStackSupport && hasStacks) { + try { + throw new Error(); + } catch (e) { + this.stack = e.stack.substring(e.stack.indexOf("\n") + 1); + } + + var self = this; + this._subscribe = function (observer) { + var oldOnError = observer.onError.bind(observer); + + observer.onError = function (err) { + makeStackTraceLong(err, self); + oldOnError(err); + }; + + return subscribe.call(self, observer); + }; + } else { + this._subscribe = subscribe; + } + } + + observableProto = Observable.prototype; + + /** + * Determines whether the given object is an Observable + * @param {Any} An object to determine whether it is an Observable + * @returns {Boolean} true if an Observable, else false. + */ + observableProto.isObservable = function (o) { + return o && isFunction(o.subscribe); + } + + /** + * Subscribes an observer to the observable sequence. + * @param {Mixed} [observerOrOnNext] The object that is to receive notifications or an action to invoke for each element in the observable sequence. + * @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence. + * @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence. + * @returns {Diposable} A disposable handling the subscriptions and unsubscriptions. + */ + observableProto.subscribe = observableProto.forEach = function (observerOrOnNext, onError, onCompleted) { + return this._subscribe(typeof observerOrOnNext === 'object' ? + observerOrOnNext : + observerCreate(observerOrOnNext, onError, onCompleted)); + }; + + /** + * Subscribes to the next value in the sequence with an optional "this" argument. + * @param {Function} onNext The function to invoke on each element in the observable sequence. + * @param {Any} [thisArg] Object to use as this when executing callback. + * @returns {Disposable} A disposable handling the subscriptions and unsubscriptions. + */ + observableProto.subscribeOnNext = function (onNext, thisArg) { + return this._subscribe(observerCreate(typeof thisArg !== 'undefined' ? function(x) { onNext.call(thisArg, x); } : onNext)); + }; + + /** + * Subscribes to an exceptional condition in the sequence with an optional "this" argument. + * @param {Function} onError The function to invoke upon exceptional termination of the observable sequence. + * @param {Any} [thisArg] Object to use as this when executing callback. + * @returns {Disposable} A disposable handling the subscriptions and unsubscriptions. + */ + observableProto.subscribeOnError = function (onError, thisArg) { + return this._subscribe(observerCreate(null, typeof thisArg !== 'undefined' ? function(e) { onError.call(thisArg, e); } : onError)); + }; + + /** + * Subscribes to the next value in the sequence with an optional "this" argument. + * @param {Function} onCompleted The function to invoke upon graceful termination of the observable sequence. + * @param {Any} [thisArg] Object to use as this when executing callback. + * @returns {Disposable} A disposable handling the subscriptions and unsubscriptions. + */ + observableProto.subscribeOnCompleted = function (onCompleted, thisArg) { + return this._subscribe(observerCreate(null, null, typeof thisArg !== 'undefined' ? function() { onCompleted.call(thisArg); } : onCompleted)); + }; + + return Observable; + })(); + + var ObservableBase = Rx.ObservableBase = (function (__super__) { + inherits(ObservableBase, __super__); + + function fixSubscriber(subscriber) { + return subscriber && isFunction(subscriber.dispose) ? subscriber : + isFunction(subscriber) ? disposableCreate(subscriber) : disposableEmpty; + } + + function setDisposable(s, state) { + var ado = state[0], self = state[1]; + var sub = tryCatch(self.subscribeCore).call(self, ado); + + if (sub === errorObj) { + if(!ado.fail(errorObj.e)) { return thrower(errorObj.e); } + } + ado.setDisposable(fixSubscriber(sub)); + } + + function subscribe(observer) { + var ado = new AutoDetachObserver(observer), state = [ado, this]; + + if (currentThreadScheduler.scheduleRequired()) { + currentThreadScheduler.scheduleWithState(state, setDisposable); + } else { + setDisposable(null, state); + } + return ado; + } + + function ObservableBase() { + __super__.call(this, subscribe); + } + + ObservableBase.prototype.subscribeCore = notImplemented; + + return ObservableBase; + }(Observable)); + + var Enumerable = Rx.internals.Enumerable = function () { }; + + var ConcatEnumerableObservable = (function(__super__) { + inherits(ConcatEnumerableObservable, __super__); + function ConcatEnumerableObservable(sources) { + this.sources = sources; + __super__.call(this); + } + + ConcatEnumerableObservable.prototype.subscribeCore = function (o) { + var isDisposed, subscription = new SerialDisposable(); + var cancelable = immediateScheduler.scheduleRecursiveWithState(this.sources[$iterator$](), function (e, self) { + if (isDisposed) { return; } + var currentItem = tryCatch(e.next).call(e); + if (currentItem === errorObj) { return o.onError(currentItem.e); } + + if (currentItem.done) { + return o.onCompleted(); + } + + // Check if promise + var currentValue = currentItem.value; + isPromise(currentValue) && (currentValue = observableFromPromise(currentValue)); + + var d = new SingleAssignmentDisposable(); + subscription.setDisposable(d); + d.setDisposable(currentValue.subscribe(new InnerObserver(o, self, e))); + }); + + return new CompositeDisposable(subscription, cancelable, disposableCreate(function () { + isDisposed = true; + })); + }; + + function InnerObserver(o, s, e) { + this.o = o; + this.s = s; + this.e = e; + this.isStopped = false; + } + InnerObserver.prototype.onNext = function (x) { if(!this.isStopped) { this.o.onNext(x); } }; + InnerObserver.prototype.onError = function (err) { + if (!this.isStopped) { + this.isStopped = true; + this.o.onError(err); + } + }; + InnerObserver.prototype.onCompleted = function () { + if (!this.isStopped) { + this.isStopped = true; + this.s(this.e); + } + }; + InnerObserver.prototype.dispose = function () { this.isStopped = true; }; + InnerObserver.prototype.fail = function (err) { + if (!this.isStopped) { + this.isStopped = true; + this.o.onError(err); + return true; + } + return false; + }; + + return ConcatEnumerableObservable; + }(ObservableBase)); + + Enumerable.prototype.concat = function () { + return new ConcatEnumerableObservable(this); + }; + + var CatchErrorObservable = (function(__super__) { + inherits(CatchErrorObservable, __super__); + function CatchErrorObservable(sources) { + this.sources = sources; + __super__.call(this); + } + + CatchErrorObservable.prototype.subscribeCore = function (o) { + var e = this.sources[$iterator$](); + + var isDisposed, subscription = new SerialDisposable(); + var cancelable = immediateScheduler.scheduleRecursiveWithState(null, function (lastException, self) { + if (isDisposed) { return; } + var currentItem = tryCatch(e.next).call(e); + if (currentItem === errorObj) { return o.onError(currentItem.e); } + + if (currentItem.done) { + return lastException !== null ? o.onError(lastException) : o.onCompleted(); + } + + // Check if promise + var currentValue = currentItem.value; + isPromise(currentValue) && (currentValue = observableFromPromise(currentValue)); + + var d = new SingleAssignmentDisposable(); + subscription.setDisposable(d); + d.setDisposable(currentValue.subscribe( + function(x) { o.onNext(x); }, + self, + function() { o.onCompleted(); })); + }); + return new CompositeDisposable(subscription, cancelable, disposableCreate(function () { + isDisposed = true; + })); + }; + + return CatchErrorObservable; + }(ObservableBase)); + + Enumerable.prototype.catchError = function () { + return new CatchErrorObservable(this); + }; + + Enumerable.prototype.catchErrorWhen = function (notificationHandler) { + var sources = this; + return new AnonymousObservable(function (o) { + var exceptions = new Subject(), + notifier = new Subject(), + handled = notificationHandler(exceptions), + notificationDisposable = handled.subscribe(notifier); + + var e = sources[$iterator$](); + + var isDisposed, + lastException, + subscription = new SerialDisposable(); + var cancelable = immediateScheduler.scheduleRecursive(function (self) { + if (isDisposed) { return; } + var currentItem = tryCatch(e.next).call(e); + if (currentItem === errorObj) { return o.onError(currentItem.e); } + + if (currentItem.done) { + if (lastException) { + o.onError(lastException); + } else { + o.onCompleted(); + } + return; + } + + // Check if promise + var currentValue = currentItem.value; + isPromise(currentValue) && (currentValue = observableFromPromise(currentValue)); + + var outer = new SingleAssignmentDisposable(); + var inner = new SingleAssignmentDisposable(); + subscription.setDisposable(new CompositeDisposable(inner, outer)); + outer.setDisposable(currentValue.subscribe( + function(x) { o.onNext(x); }, + function (exn) { + inner.setDisposable(notifier.subscribe(self, function(ex) { + o.onError(ex); + }, function() { + o.onCompleted(); + })); + + exceptions.onNext(exn); + }, + function() { o.onCompleted(); })); + }); + + return new CompositeDisposable(notificationDisposable, subscription, cancelable, disposableCreate(function () { + isDisposed = true; + })); + }); + }; + + var RepeatEnumerable = (function (__super__) { + inherits(RepeatEnumerable, __super__); + + function RepeatEnumerable(v, c) { + this.v = v; + this.c = c == null ? -1 : c; + } + RepeatEnumerable.prototype[$iterator$] = function () { + return new RepeatEnumerator(this); + }; + + function RepeatEnumerator(p) { + this.v = p.v; + this.l = p.c; + } + RepeatEnumerator.prototype.next = function () { + if (this.l === 0) { return doneEnumerator; } + if (this.l > 0) { this.l--; } + return { done: false, value: this.v }; + }; + + return RepeatEnumerable; + }(Enumerable)); + + var enumerableRepeat = Enumerable.repeat = function (value, repeatCount) { + return new RepeatEnumerable(value, repeatCount); + }; + + var OfEnumerable = (function(__super__) { + inherits(OfEnumerable, __super__); + function OfEnumerable(s, fn, thisArg) { + this.s = s; + this.fn = fn ? bindCallback(fn, thisArg, 3) : null; + } + OfEnumerable.prototype[$iterator$] = function () { + return new OfEnumerator(this); + }; + + function OfEnumerator(p) { + this.i = -1; + this.s = p.s; + this.l = this.s.length; + this.fn = p.fn; + } + OfEnumerator.prototype.next = function () { + return ++this.i < this.l ? + { done: false, value: !this.fn ? this.s[this.i] : this.fn(this.s[this.i], this.i, this.s) } : + doneEnumerator; + }; + + return OfEnumerable; + }(Enumerable)); + + var enumerableOf = Enumerable.of = function (source, selector, thisArg) { + return new OfEnumerable(source, selector, thisArg); + }; + + /** + * Wraps the source sequence in order to run its observer callbacks on the specified scheduler. + * + * This only invokes observer callbacks on a scheduler. In case the subscription and/or unsubscription actions have side-effects + * that require to be run on a scheduler, use subscribeOn. + * + * @param {Scheduler} scheduler Scheduler to notify observers on. + * @returns {Observable} The source sequence whose observations happen on the specified scheduler. + */ + observableProto.observeOn = function (scheduler) { + var source = this; + return new AnonymousObservable(function (observer) { + return source.subscribe(new ObserveOnObserver(scheduler, observer)); + }, source); + }; + + /** + * Wraps the source sequence in order to run its subscription and unsubscription logic on the specified scheduler. This operation is not commonly used; + * see the remarks section for more information on the distinction between subscribeOn and observeOn. + + * This only performs the side-effects of subscription and unsubscription on the specified scheduler. In order to invoke observer + * callbacks on a scheduler, use observeOn. + + * @param {Scheduler} scheduler Scheduler to perform subscription and unsubscription actions on. + * @returns {Observable} The source sequence whose subscriptions and unsubscriptions happen on the specified scheduler. + */ + observableProto.subscribeOn = function (scheduler) { + var source = this; + return new AnonymousObservable(function (observer) { + var m = new SingleAssignmentDisposable(), d = new SerialDisposable(); + d.setDisposable(m); + m.setDisposable(scheduler.schedule(function () { + d.setDisposable(new ScheduledDisposable(scheduler, source.subscribe(observer))); + })); + return d; + }, source); + }; + + var FromPromiseObservable = (function(__super__) { + inherits(FromPromiseObservable, __super__); + function FromPromiseObservable(p) { + this.p = p; + __super__.call(this); + } + + FromPromiseObservable.prototype.subscribeCore = function(o) { + this.p.then(function (data) { + o.onNext(data); + o.onCompleted(); + }, function (err) { o.onError(err); }); + return disposableEmpty; + }; + + return FromPromiseObservable; + }(ObservableBase)); + + /** + * Converts a Promise to an Observable sequence + * @param {Promise} An ES6 Compliant promise. + * @returns {Observable} An Observable sequence which wraps the existing promise success and failure. + */ + var observableFromPromise = Observable.fromPromise = function (promise) { + return new FromPromiseObservable(promise); + }; + /* + * Converts an existing observable sequence to an ES6 Compatible Promise + * @example + * var promise = Rx.Observable.return(42).toPromise(RSVP.Promise); + * + * // With config + * Rx.config.Promise = RSVP.Promise; + * var promise = Rx.Observable.return(42).toPromise(); + * @param {Function} [promiseCtor] The constructor of the promise. If not provided, it looks for it in Rx.config.Promise. + * @returns {Promise} An ES6 compatible promise with the last value from the observable sequence. + */ + observableProto.toPromise = function (promiseCtor) { + promiseCtor || (promiseCtor = Rx.config.Promise); + if (!promiseCtor) { throw new NotSupportedError('Promise type not provided nor in Rx.config.Promise'); } + var source = this; + return new promiseCtor(function (resolve, reject) { + // No cancellation can be done + var value, hasValue = false; + source.subscribe(function (v) { + value = v; + hasValue = true; + }, reject, function () { + hasValue && resolve(value); + }); + }); + }; + + var ToArrayObservable = (function(__super__) { + inherits(ToArrayObservable, __super__); + function ToArrayObservable(source) { + this.source = source; + __super__.call(this); + } + + ToArrayObservable.prototype.subscribeCore = function(o) { + return this.source.subscribe(new InnerObserver(o)); + }; + + function InnerObserver(o) { + this.o = o; + this.a = []; + this.isStopped = false; + } + InnerObserver.prototype.onNext = function (x) { if(!this.isStopped) { this.a.push(x); } }; + InnerObserver.prototype.onError = function (e) { + if (!this.isStopped) { + this.isStopped = true; + this.o.onError(e); + } + }; + InnerObserver.prototype.onCompleted = function () { + if (!this.isStopped) { + this.isStopped = true; + this.o.onNext(this.a); + this.o.onCompleted(); + } + }; + InnerObserver.prototype.dispose = function () { this.isStopped = true; } + InnerObserver.prototype.fail = function (e) { + if (!this.isStopped) { + this.isStopped = true; + this.o.onError(e); + return true; + } + + return false; + }; + + return ToArrayObservable; + }(ObservableBase)); + + /** + * Creates an array from an observable sequence. + * @returns {Observable} An observable sequence containing a single element with a list containing all the elements of the source sequence. + */ + observableProto.toArray = function () { + return new ToArrayObservable(this); + }; + + /** + * Creates an observable sequence from a specified subscribe method implementation. + * @example + * var res = Rx.Observable.create(function (observer) { return function () { } ); + * var res = Rx.Observable.create(function (observer) { return Rx.Disposable.empty; } ); + * var res = Rx.Observable.create(function (observer) { } ); + * @param {Function} subscribe Implementation of the resulting observable sequence's subscribe method, returning a function that will be wrapped in a Disposable. + * @returns {Observable} The observable sequence with the specified implementation for the Subscribe method. + */ + Observable.create = Observable.createWithDisposable = function (subscribe, parent) { + return new AnonymousObservable(subscribe, parent); + }; + + /** + * Returns an observable sequence that invokes the specified factory function whenever a new observer subscribes. + * + * @example + * var res = Rx.Observable.defer(function () { return Rx.Observable.fromArray([1,2,3]); }); + * @param {Function} observableFactory Observable factory function to invoke for each observer that subscribes to the resulting sequence or Promise. + * @returns {Observable} An observable sequence whose observers trigger an invocation of the given observable factory function. + */ + var observableDefer = Observable.defer = function (observableFactory) { + return new AnonymousObservable(function (observer) { + var result; + try { + result = observableFactory(); + } catch (e) { + return observableThrow(e).subscribe(observer); + } + isPromise(result) && (result = observableFromPromise(result)); + return result.subscribe(observer); + }); + }; + + var EmptyObservable = (function(__super__) { + inherits(EmptyObservable, __super__); + function EmptyObservable(scheduler) { + this.scheduler = scheduler; + __super__.call(this); + } + + EmptyObservable.prototype.subscribeCore = function (observer) { + var sink = new EmptySink(observer, this); + return sink.run(); + }; + + function EmptySink(observer, parent) { + this.observer = observer; + this.parent = parent; + } + + function scheduleItem(s, state) { + state.onCompleted(); + } + + EmptySink.prototype.run = function () { + return this.parent.scheduler.scheduleWithState(this.observer, scheduleItem); + }; + + return EmptyObservable; + }(ObservableBase)); + + /** + * Returns an empty observable sequence, using the specified scheduler to send out the single OnCompleted message. + * + * @example + * var res = Rx.Observable.empty(); + * var res = Rx.Observable.empty(Rx.Scheduler.timeout); + * @param {Scheduler} [scheduler] Scheduler to send the termination call on. + * @returns {Observable} An observable sequence with no elements. + */ + var observableEmpty = Observable.empty = function (scheduler) { + isScheduler(scheduler) || (scheduler = immediateScheduler); + return new EmptyObservable(scheduler); + }; + + var FromObservable = (function(__super__) { + inherits(FromObservable, __super__); + function FromObservable(iterable, mapper, scheduler) { + this.iterable = iterable; + this.mapper = mapper; + this.scheduler = scheduler; + __super__.call(this); + } + + FromObservable.prototype.subscribeCore = function (observer) { + var sink = new FromSink(observer, this); + return sink.run(); + }; + + return FromObservable; + }(ObservableBase)); + + var FromSink = (function () { + function FromSink(observer, parent) { + this.observer = observer; + this.parent = parent; + } + + FromSink.prototype.run = function () { + var list = Object(this.parent.iterable), + it = getIterable(list), + observer = this.observer, + mapper = this.parent.mapper; + + function loopRecursive(i, recurse) { + try { + var next = it.next(); + } catch (e) { + return observer.onError(e); + } + if (next.done) { + return observer.onCompleted(); + } + + var result = next.value; + + if (mapper) { + try { + result = mapper(result, i); + } catch (e) { + return observer.onError(e); + } + } + + observer.onNext(result); + recurse(i + 1); + } + + return this.parent.scheduler.scheduleRecursiveWithState(0, loopRecursive); + }; + + return FromSink; + }()); + + var maxSafeInteger = Math.pow(2, 53) - 1; + + function StringIterable(str) { + this._s = s; + } + + StringIterable.prototype[$iterator$] = function () { + return new StringIterator(this._s); + }; + + function StringIterator(str) { + this._s = s; + this._l = s.length; + this._i = 0; + } + + StringIterator.prototype[$iterator$] = function () { + return this; + }; + + StringIterator.prototype.next = function () { + return this._i < this._l ? { done: false, value: this._s.charAt(this._i++) } : doneEnumerator; + }; + + function ArrayIterable(a) { + this._a = a; + } + + ArrayIterable.prototype[$iterator$] = function () { + return new ArrayIterator(this._a); + }; + + function ArrayIterator(a) { + this._a = a; + this._l = toLength(a); + this._i = 0; + } + + ArrayIterator.prototype[$iterator$] = function () { + return this; + }; + + ArrayIterator.prototype.next = function () { + return this._i < this._l ? { done: false, value: this._a[this._i++] } : doneEnumerator; + }; + + function numberIsFinite(value) { + return typeof value === 'number' && root.isFinite(value); + } + + function isNan(n) { + return n !== n; + } + + function getIterable(o) { + var i = o[$iterator$], it; + if (!i && typeof o === 'string') { + it = new StringIterable(o); + return it[$iterator$](); + } + if (!i && o.length !== undefined) { + it = new ArrayIterable(o); + return it[$iterator$](); + } + if (!i) { throw new TypeError('Object is not iterable'); } + return o[$iterator$](); + } + + function sign(value) { + var number = +value; + if (number === 0) { return number; } + if (isNaN(number)) { return number; } + return number < 0 ? -1 : 1; + } + + function toLength(o) { + var len = +o.length; + if (isNaN(len)) { return 0; } + if (len === 0 || !numberIsFinite(len)) { return len; } + len = sign(len) * Math.floor(Math.abs(len)); + if (len <= 0) { return 0; } + if (len > maxSafeInteger) { return maxSafeInteger; } + return len; + } + + /** + * This method creates a new Observable sequence from an array-like or iterable object. + * @param {Any} arrayLike An array-like or iterable object to convert to an Observable sequence. + * @param {Function} [mapFn] Map function to call on every element of the array. + * @param {Any} [thisArg] The context to use calling the mapFn if provided. + * @param {Scheduler} [scheduler] Optional scheduler to use for scheduling. If not provided, defaults to Scheduler.currentThread. + */ + var observableFrom = Observable.from = function (iterable, mapFn, thisArg, scheduler) { + if (iterable == null) { + throw new Error('iterable cannot be null.') + } + if (mapFn && !isFunction(mapFn)) { + throw new Error('mapFn when provided must be a function'); + } + if (mapFn) { + var mapper = bindCallback(mapFn, thisArg, 2); + } + isScheduler(scheduler) || (scheduler = currentThreadScheduler); + return new FromObservable(iterable, mapper, scheduler); + } + + var FromArrayObservable = (function(__super__) { + inherits(FromArrayObservable, __super__); + function FromArrayObservable(args, scheduler) { + this.args = args; + this.scheduler = scheduler; + __super__.call(this); + } + + FromArrayObservable.prototype.subscribeCore = function (observer) { + var sink = new FromArraySink(observer, this); + return sink.run(); + }; + + return FromArrayObservable; + }(ObservableBase)); + + function FromArraySink(observer, parent) { + this.observer = observer; + this.parent = parent; + } + + FromArraySink.prototype.run = function () { + var observer = this.observer, args = this.parent.args, len = args.length; + function loopRecursive(i, recurse) { + if (i < len) { + observer.onNext(args[i]); + recurse(i + 1); + } else { + observer.onCompleted(); + } + } + + return this.parent.scheduler.scheduleRecursiveWithState(0, loopRecursive); + }; + + /** + * Converts an array to an observable sequence, using an optional scheduler to enumerate the array. + * @deprecated use Observable.from or Observable.of + * @param {Scheduler} [scheduler] Scheduler to run the enumeration of the input sequence on. + * @returns {Observable} The observable sequence whose elements are pulled from the given enumerable sequence. + */ + var observableFromArray = Observable.fromArray = function (array, scheduler) { + isScheduler(scheduler) || (scheduler = currentThreadScheduler); + return new FromArrayObservable(array, scheduler) + }; + + /** + * Generates an observable sequence by running a state-driven loop producing the sequence's elements, using the specified scheduler to send out observer messages. + * + * @example + * var res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; }); + * var res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; }, Rx.Scheduler.timeout); + * @param {Mixed} initialState Initial state. + * @param {Function} condition Condition to terminate generation (upon returning false). + * @param {Function} iterate Iteration step function. + * @param {Function} resultSelector Selector function for results produced in the sequence. + * @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not provided, defaults to Scheduler.currentThread. + * @returns {Observable} The generated sequence. + */ + Observable.generate = function (initialState, condition, iterate, resultSelector, scheduler) { + isScheduler(scheduler) || (scheduler = currentThreadScheduler); + return new AnonymousObservable(function (o) { + var first = true; + return scheduler.scheduleRecursiveWithState(initialState, function (state, self) { + var hasResult, result; + try { + if (first) { + first = false; + } else { + state = iterate(state); + } + hasResult = condition(state); + hasResult && (result = resultSelector(state)); + } catch (e) { + return o.onError(e); + } + if (hasResult) { + o.onNext(result); + self(state); + } else { + o.onCompleted(); + } + }); + }); + }; + + function observableOf (scheduler, array) { + isScheduler(scheduler) || (scheduler = currentThreadScheduler); + return new FromArrayObservable(array, scheduler); + } + + /** + * This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments. + * @returns {Observable} The observable sequence whose elements are pulled from the given arguments. + */ + Observable.of = function () { + var len = arguments.length, args = new Array(len); + for(var i = 0; i < len; i++) { args[i] = arguments[i]; } + return new FromArrayObservable(args, currentThreadScheduler); + }; + + /** + * This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments. + * @param {Scheduler} scheduler A scheduler to use for scheduling the arguments. + * @returns {Observable} The observable sequence whose elements are pulled from the given arguments. + */ + Observable.ofWithScheduler = function (scheduler) { + var len = arguments.length, args = new Array(len - 1); + for(var i = 1; i < len; i++) { args[i - 1] = arguments[i]; } + return new FromArrayObservable(args, scheduler); + }; + + /** + * Creates an Observable sequence from changes to an array using Array.observe. + * @param {Array} array An array to observe changes. + * @returns {Observable} An observable sequence containing changes to an array from Array.observe. + */ + Observable.ofArrayChanges = function(array) { + if (!Array.isArray(array)) { throw new TypeError('Array.observe only accepts arrays.'); } + if (typeof Array.observe !== 'function' && typeof Array.unobserve !== 'function') { throw new TypeError('Array.observe is not supported on your platform') } + return new AnonymousObservable(function(observer) { + function observerFn(changes) { + for(var i = 0, len = changes.length; i < len; i++) { + observer.onNext(changes[i]); + } + } + + Array.observe(array, observerFn); + + return function () { + Array.unobserve(array, observerFn); + }; + }); + }; + + /** + * Creates an Observable sequence from changes to an object using Object.observe. + * @param {Object} obj An object to observe changes. + * @returns {Observable} An observable sequence containing changes to an object from Object.observe. + */ + Observable.ofObjectChanges = function(obj) { + if (obj == null) { throw new TypeError('object must not be null or undefined.'); } + if (typeof Object.observe !== 'function' && typeof Object.unobserve !== 'function') { throw new TypeError('Object.observe is not supported on your platform') } + return new AnonymousObservable(function(observer) { + function observerFn(changes) { + for(var i = 0, len = changes.length; i < len; i++) { + observer.onNext(changes[i]); + } + } + + Object.observe(obj, observerFn); + + return function () { + Object.unobserve(obj, observerFn); + }; + }); + }; + + var NeverObservable = (function(__super__) { + inherits(NeverObservable, __super__); + function NeverObservable() { + __super__.call(this); + } + + NeverObservable.prototype.subscribeCore = function (observer) { + return disposableEmpty; + }; + + return NeverObservable; + }(ObservableBase)); + + /** + * Returns a non-terminating observable sequence, which can be used to denote an infinite duration (e.g. when using reactive joins). + * @returns {Observable} An observable sequence whose observers will never get called. + */ + var observableNever = Observable.never = function () { + return new NeverObservable(); + }; + + var PairsObservable = (function(__super__) { + inherits(PairsObservable, __super__); + function PairsObservable(obj, scheduler) { + this.obj = obj; + this.keys = Object.keys(obj); + this.scheduler = scheduler; + __super__.call(this); + } + + PairsObservable.prototype.subscribeCore = function (observer) { + var sink = new PairsSink(observer, this); + return sink.run(); + }; + + return PairsObservable; + }(ObservableBase)); + + function PairsSink(observer, parent) { + this.observer = observer; + this.parent = parent; + } + + PairsSink.prototype.run = function () { + var observer = this.observer, obj = this.parent.obj, keys = this.parent.keys, len = keys.length; + function loopRecursive(i, recurse) { + if (i < len) { + var key = keys[i]; + observer.onNext([key, obj[key]]); + recurse(i + 1); + } else { + observer.onCompleted(); + } + } + + return this.parent.scheduler.scheduleRecursiveWithState(0, loopRecursive); + }; + + /** + * Convert an object into an observable sequence of [key, value] pairs. + * @param {Object} obj The object to inspect. + * @param {Scheduler} [scheduler] Scheduler to run the enumeration of the input sequence on. + * @returns {Observable} An observable sequence of [key, value] pairs from the object. + */ + Observable.pairs = function (obj, scheduler) { + scheduler || (scheduler = currentThreadScheduler); + return new PairsObservable(obj, scheduler); + }; + + var RangeObservable = (function(__super__) { + inherits(RangeObservable, __super__); + function RangeObservable(start, count, scheduler) { + this.start = start; + this.rangeCount = count; + this.scheduler = scheduler; + __super__.call(this); + } + + RangeObservable.prototype.subscribeCore = function (observer) { + var sink = new RangeSink(observer, this); + return sink.run(); + }; + + return RangeObservable; + }(ObservableBase)); + + var RangeSink = (function () { + function RangeSink(observer, parent) { + this.observer = observer; + this.parent = parent; + } + + RangeSink.prototype.run = function () { + var start = this.parent.start, count = this.parent.rangeCount, observer = this.observer; + function loopRecursive(i, recurse) { + if (i < count) { + observer.onNext(start + i); + recurse(i + 1); + } else { + observer.onCompleted(); + } + } + + return this.parent.scheduler.scheduleRecursiveWithState(0, loopRecursive); + }; + + return RangeSink; + }()); + + /** + * Generates an observable sequence of integral numbers within a specified range, using the specified scheduler to send out observer messages. + * @param {Number} start The value of the first integer in the sequence. + * @param {Number} count The number of sequential integers to generate. + * @param {Scheduler} [scheduler] Scheduler to run the generator loop on. If not specified, defaults to Scheduler.currentThread. + * @returns {Observable} An observable sequence that contains a range of sequential integral numbers. + */ + Observable.range = function (start, count, scheduler) { + isScheduler(scheduler) || (scheduler = currentThreadScheduler); + return new RangeObservable(start, count, scheduler); + }; + + var RepeatObservable = (function(__super__) { + inherits(RepeatObservable, __super__); + function RepeatObservable(value, repeatCount, scheduler) { + this.value = value; + this.repeatCount = repeatCount == null ? -1 : repeatCount; + this.scheduler = scheduler; + __super__.call(this); + } + + RepeatObservable.prototype.subscribeCore = function (observer) { + var sink = new RepeatSink(observer, this); + return sink.run(); + }; + + return RepeatObservable; + }(ObservableBase)); + + function RepeatSink(observer, parent) { + this.observer = observer; + this.parent = parent; + } + + RepeatSink.prototype.run = function () { + var observer = this.observer, value = this.parent.value; + function loopRecursive(i, recurse) { + if (i === -1 || i > 0) { + observer.onNext(value); + i > 0 && i--; + } + if (i === 0) { return observer.onCompleted(); } + recurse(i); + } + + return this.parent.scheduler.scheduleRecursiveWithState(this.parent.repeatCount, loopRecursive); + }; + + /** + * Generates an observable sequence that repeats the given element the specified number of times, using the specified scheduler to send out observer messages. + * @param {Mixed} value Element to repeat. + * @param {Number} repeatCount [Optiona] Number of times to repeat the element. If not specified, repeats indefinitely. + * @param {Scheduler} scheduler Scheduler to run the producer loop on. If not specified, defaults to Scheduler.immediate. + * @returns {Observable} An observable sequence that repeats the given element the specified number of times. + */ + Observable.repeat = function (value, repeatCount, scheduler) { + isScheduler(scheduler) || (scheduler = currentThreadScheduler); + return new RepeatObservable(value, repeatCount, scheduler); + }; + + var JustObservable = (function(__super__) { + inherits(JustObservable, __super__); + function JustObservable(value, scheduler) { + this.value = value; + this.scheduler = scheduler; + __super__.call(this); + } + + JustObservable.prototype.subscribeCore = function (observer) { + var sink = new JustSink(observer, this); + return sink.run(); + }; + + function JustSink(observer, parent) { + this.observer = observer; + this.parent = parent; + } + + function scheduleItem(s, state) { + var value = state[0], observer = state[1]; + observer.onNext(value); + observer.onCompleted(); + } + + JustSink.prototype.run = function () { + return this.parent.scheduler.scheduleWithState([this.parent.value, this.observer], scheduleItem); + }; + + return JustObservable; + }(ObservableBase)); + + /** + * Returns an observable sequence that contains a single element, using the specified scheduler to send out observer messages. + * There is an alias called 'just' or browsers 0) { + parent.handleSubscribe(parent.q.shift()); + } else { + parent.activeCount--; + parent.done && parent.activeCount === 0 && parent.o.onCompleted(); + } + } + }; + InnerObserver.prototype.dispose = function() { this.isStopped = true; }; + InnerObserver.prototype.fail = function (e) { + if (!this.isStopped) { + this.isStopped = true; + this.parent.o.onError(e); + return true; + } + + return false; + }; + + return MergeObserver; + }()); + + + + + + /** + * Merges an observable sequence of observable sequences into an observable sequence, limiting the number of concurrent subscriptions to inner sequences. + * Or merges two observable sequences into a single observable sequence. + * + * @example + * 1 - merged = sources.merge(1); + * 2 - merged = source.merge(otherSource); + * @param {Mixed} [maxConcurrentOrOther] Maximum number of inner observable sequences being subscribed to concurrently or the second observable sequence. + * @returns {Observable} The observable sequence that merges the elements of the inner sequences. + */ + observableProto.merge = function (maxConcurrentOrOther) { + return typeof maxConcurrentOrOther !== 'number' ? + observableMerge(this, maxConcurrentOrOther) : + new MergeObservable(this, maxConcurrentOrOther); + }; + + /** + * Merges all the observable sequences into a single observable sequence. + * The scheduler is optional and if not specified, the immediate scheduler is used. + * @returns {Observable} The observable sequence that merges the elements of the observable sequences. + */ + var observableMerge = Observable.merge = function () { + var scheduler, sources = [], i, len = arguments.length; + if (!arguments[0]) { + scheduler = immediateScheduler; + for(i = 1; i < len; i++) { sources.push(arguments[i]); } + } else if (isScheduler(arguments[0])) { + scheduler = arguments[0]; + for(i = 1; i < len; i++) { sources.push(arguments[i]); } + } else { + scheduler = immediateScheduler; + for(i = 0; i < len; i++) { sources.push(arguments[i]); } + } + if (Array.isArray(sources[0])) { + sources = sources[0]; + } + return observableOf(scheduler, sources).mergeAll(); + }; + + var MergeAllObservable = (function (__super__) { + inherits(MergeAllObservable, __super__); + + function MergeAllObservable(source) { + this.source = source; + __super__.call(this); + } + + MergeAllObservable.prototype.subscribeCore = function (observer) { + var g = new CompositeDisposable(), m = new SingleAssignmentDisposable(); + g.add(m); + m.setDisposable(this.source.subscribe(new MergeAllObserver(observer, g))); + return g; + }; + + function MergeAllObserver(o, g) { + this.o = o; + this.g = g; + this.isStopped = false; + this.done = false; + } + MergeAllObserver.prototype.onNext = function(innerSource) { + if(this.isStopped) { return; } + var sad = new SingleAssignmentDisposable(); + this.g.add(sad); + + isPromise(innerSource) && (innerSource = observableFromPromise(innerSource)); + + sad.setDisposable(innerSource.subscribe(new InnerObserver(this, this.g, sad))); + }; + MergeAllObserver.prototype.onError = function (e) { + if(!this.isStopped) { + this.isStopped = true; + this.o.onError(e); + } + }; + MergeAllObserver.prototype.onCompleted = function () { + if(!this.isStopped) { + this.isStopped = true; + this.done = true; + this.g.length === 1 && this.o.onCompleted(); + } + }; + MergeAllObserver.prototype.dispose = function() { this.isStopped = true; }; + MergeAllObserver.prototype.fail = function (e) { + if (!this.isStopped) { + this.isStopped = true; + this.o.onError(e); + return true; + } + + return false; + }; + + function InnerObserver(parent, g, sad) { + this.parent = parent; + this.g = g; + this.sad = sad; + this.isStopped = false; + } + InnerObserver.prototype.onNext = function (x) { if (!this.isStopped) { this.parent.o.onNext(x); } }; + InnerObserver.prototype.onError = function (e) { + if(!this.isStopped) { + this.isStopped = true; + this.parent.o.onError(e); + } + }; + InnerObserver.prototype.onCompleted = function () { + if(!this.isStopped) { + var parent = this.parent; + this.isStopped = true; + parent.g.remove(this.sad); + parent.done && parent.g.length === 1 && parent.o.onCompleted(); + } + }; + InnerObserver.prototype.dispose = function() { this.isStopped = true; }; + InnerObserver.prototype.fail = function (e) { + if (!this.isStopped) { + this.isStopped = true; + this.parent.o.onError(e); + return true; + } + + return false; + }; + + return MergeAllObservable; + }(ObservableBase)); + + /** + * Merges an observable sequence of observable sequences into an observable sequence. + * @returns {Observable} The observable sequence that merges the elements of the inner sequences. + */ + observableProto.mergeAll = observableProto.mergeObservable = function () { + return new MergeAllObservable(this); + }; + + var CompositeError = Rx.CompositeError = function(errors) { + this.name = "NotImplementedError"; + this.innerErrors = errors; + this.message = 'This contains multiple errors. Check the innerErrors'; + Error.call(this); + } + CompositeError.prototype = Error.prototype; + + /** + * Flattens an Observable that emits Observables into one Observable, in a way that allows an Observer to + * receive all successfully emitted items from all of the source Observables without being interrupted by + * an error notification from one of them. + * + * This behaves like Observable.prototype.mergeAll except that if any of the merged Observables notify of an + * error via the Observer's onError, mergeDelayError will refrain from propagating that + * error notification until all of the merged Observables have finished emitting items. + * @param {Array | Arguments} args Arguments or an array to merge. + * @returns {Observable} an Observable that emits all of the items emitted by the Observables emitted by the Observable + */ + Observable.mergeDelayError = function() { + var args; + if (Array.isArray(arguments[0])) { + args = arguments[0]; + } else { + var len = arguments.length; + args = new Array(len); + for(var i = 0; i < len; i++) { args[i] = arguments[i]; } + } + var source = observableOf(null, args); + + return new AnonymousObservable(function (o) { + var group = new CompositeDisposable(), + m = new SingleAssignmentDisposable(), + isStopped = false, + errors = []; + + function setCompletion() { + if (errors.length === 0) { + o.onCompleted(); + } else if (errors.length === 1) { + o.onError(errors[0]); + } else { + o.onError(new CompositeError(errors)); + } + } + + group.add(m); + + m.setDisposable(source.subscribe( + function (innerSource) { + var innerSubscription = new SingleAssignmentDisposable(); + group.add(innerSubscription); + + // Check for promises support + isPromise(innerSource) && (innerSource = observableFromPromise(innerSource)); + + innerSubscription.setDisposable(innerSource.subscribe( + function (x) { o.onNext(x); }, + function (e) { + errors.push(e); + group.remove(innerSubscription); + isStopped && group.length === 1 && setCompletion(); + }, + function () { + group.remove(innerSubscription); + isStopped && group.length === 1 && setCompletion(); + })); + }, + function (e) { + errors.push(e); + isStopped = true; + group.length === 1 && setCompletion(); + }, + function () { + isStopped = true; + group.length === 1 && setCompletion(); + })); + return group; + }); + }; + + /** + * Continues an observable sequence that is terminated normally or by an exception with the next observable sequence. + * @param {Observable} second Second observable sequence used to produce results after the first sequence terminates. + * @returns {Observable} An observable sequence that concatenates the first and second sequence, even if the first sequence terminates exceptionally. + */ + observableProto.onErrorResumeNext = function (second) { + if (!second) { throw new Error('Second observable is required'); } + return onErrorResumeNext([this, second]); + }; + + /** + * Continues an observable sequence that is terminated normally or by an exception with the next observable sequence. + * + * @example + * 1 - res = Rx.Observable.onErrorResumeNext(xs, ys, zs); + * 1 - res = Rx.Observable.onErrorResumeNext([xs, ys, zs]); + * @returns {Observable} An observable sequence that concatenates the source sequences, even if a sequence terminates exceptionally. + */ + var onErrorResumeNext = Observable.onErrorResumeNext = function () { + var sources = []; + if (Array.isArray(arguments[0])) { + sources = arguments[0]; + } else { + for(var i = 0, len = arguments.length; i < len; i++) { sources.push(arguments[i]); } + } + return new AnonymousObservable(function (observer) { + var pos = 0, subscription = new SerialDisposable(), + cancelable = immediateScheduler.scheduleRecursive(function (self) { + var current, d; + if (pos < sources.length) { + current = sources[pos++]; + isPromise(current) && (current = observableFromPromise(current)); + d = new SingleAssignmentDisposable(); + subscription.setDisposable(d); + d.setDisposable(current.subscribe(observer.onNext.bind(observer), self, self)); + } else { + observer.onCompleted(); + } + }); + return new CompositeDisposable(subscription, cancelable); + }); + }; + + /** + * Returns the values from the source observable sequence only after the other observable sequence produces a value. + * @param {Observable | Promise} other The observable sequence or Promise that triggers propagation of elements of the source sequence. + * @returns {Observable} An observable sequence containing the elements of the source sequence starting from the point the other sequence triggered propagation. + */ + observableProto.skipUntil = function (other) { + var source = this; + return new AnonymousObservable(function (o) { + var isOpen = false; + var disposables = new CompositeDisposable(source.subscribe(function (left) { + isOpen && o.onNext(left); + }, function (e) { o.onError(e); }, function () { + isOpen && o.onCompleted(); + })); + + isPromise(other) && (other = observableFromPromise(other)); + + var rightSubscription = new SingleAssignmentDisposable(); + disposables.add(rightSubscription); + rightSubscription.setDisposable(other.subscribe(function () { + isOpen = true; + rightSubscription.dispose(); + }, function (e) { o.onError(e); }, function () { + rightSubscription.dispose(); + })); + + return disposables; + }, source); + }; + + var SwitchObservable = (function(__super__) { + inherits(SwitchObservable, __super__); + function SwitchObservable(source) { + this.source = source; + __super__.call(this); + } + + SwitchObservable.prototype.subscribeCore = function (o) { + var inner = new SerialDisposable(), s = this.source.subscribe(new SwitchObserver(o, inner)); + return new CompositeDisposable(s, inner); + }; + + function SwitchObserver(o, inner) { + this.o = o; + this.inner = inner; + this.stopped = false; + this.latest = 0; + this.hasLatest = false; + this.isStopped = false; + } + SwitchObserver.prototype.onNext = function (innerSource) { + if (this.isStopped) { return; } + var d = new SingleAssignmentDisposable(), id = ++this.latest; + this.hasLatest = true; + this.inner.setDisposable(d); + isPromise(innerSource) && (innerSource = observableFromPromise(innerSource)); + d.setDisposable(innerSource.subscribe(new InnerObserver(this, id))); + }; + SwitchObserver.prototype.onError = function (e) { + if (!this.isStopped) { + this.isStopped = true; + this.o.onError(e); + } + }; + SwitchObserver.prototype.onCompleted = function () { + if (!this.isStopped) { + this.isStopped = true; + this.stopped = true; + !this.hasLatest && this.o.onCompleted(); + } + }; + SwitchObserver.prototype.dispose = function () { this.isStopped = true; }; + SwitchObserver.prototype.fail = function (e) { + if(!this.isStopped) { + this.isStopped = true; + this.o.onError(e); + return true; + } + return false; + }; + + function InnerObserver(parent, id) { + this.parent = parent; + this.id = id; + this.isStopped = false; + } + InnerObserver.prototype.onNext = function (x) { + if (this.isStopped) { return; } + this.parent.latest === this.id && this.parent.o.onNext(x); + }; + InnerObserver.prototype.onError = function (e) { + if (!this.isStopped) { + this.isStopped = true; + this.parent.latest === this.id && this.parent.o.onError(e); + } + }; + InnerObserver.prototype.onCompleted = function () { + if (!this.isStopped) { + this.isStopped = true; + if (this.parent.latest === this.id) { + this.parent.hasLatest = false; + this.parent.isStopped && this.parent.o.onCompleted(); + } + } + }; + InnerObserver.prototype.dispose = function () { this.isStopped = true; } + InnerObserver.prototype.fail = function (e) { + if(!this.isStopped) { + this.isStopped = true; + this.parent.o.onError(e); + return true; + } + return false; + }; + + return SwitchObservable; + }(ObservableBase)); + + /** + * Transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence. + * @returns {Observable} The observable sequence that at any point in time produces the elements of the most recent inner observable sequence that has been received. + */ + observableProto['switch'] = observableProto.switchLatest = function () { + return new SwitchObservable(this); + }; + + var TakeUntilObservable = (function(__super__) { + inherits(TakeUntilObservable, __super__); + + function TakeUntilObservable(source, other) { + this.source = source; + this.other = isPromise(other) ? observableFromPromise(other) : other; + __super__.call(this); + } + + TakeUntilObservable.prototype.subscribeCore = function(o) { + return new CompositeDisposable( + this.source.subscribe(o), + this.other.subscribe(new InnerObserver(o)) + ); + }; + + function InnerObserver(o) { + this.o = o; + this.isStopped = false; + } + InnerObserver.prototype.onNext = function (x) { + if (this.isStopped) { return; } + this.o.onCompleted(); + }; + InnerObserver.prototype.onError = function (err) { + if (!this.isStopped) { + this.isStopped = true; + this.o.onError(err); + } + }; + InnerObserver.prototype.onCompleted = function () { + !this.isStopped && (this.isStopped = true); + }; + InnerObserver.prototype.dispose = function() { this.isStopped = true; }; + InnerObserver.prototype.fail = function (e) { + if (!this.isStopped) { + this.isStopped = true; + this.o.onError(e); + return true; + } + return false; + }; + + return TakeUntilObservable; + }(ObservableBase)); + + /** + * Returns the values from the source observable sequence until the other observable sequence produces a value. + * @param {Observable | Promise} other Observable sequence or Promise that terminates propagation of elements of the source sequence. + * @returns {Observable} An observable sequence containing the elements of the source sequence up to the point the other sequence interrupted further propagation. + */ + observableProto.takeUntil = function (other) { + return new TakeUntilObservable(this, other); + }; + + function falseFactory() { return false; } + + /** + * Merges the specified observable sequences into one observable sequence by using the selector function only when the (first) source observable sequence produces an element. + * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + observableProto.withLatestFrom = function () { + var len = arguments.length, args = new Array(len) + for(var i = 0; i < len; i++) { args[i] = arguments[i]; } + var resultSelector = args.pop(), source = this; + Array.isArray(args[0]) && (args = args[0]); + + return new AnonymousObservable(function (observer) { + var n = args.length, + hasValue = arrayInitialize(n, falseFactory), + hasValueAll = false, + values = new Array(n); + + var subscriptions = new Array(n + 1); + for (var idx = 0; idx < n; idx++) { + (function (i) { + var other = args[i], sad = new SingleAssignmentDisposable(); + isPromise(other) && (other = observableFromPromise(other)); + sad.setDisposable(other.subscribe(function (x) { + values[i] = x; + hasValue[i] = true; + hasValueAll = hasValue.every(identity); + }, function (e) { observer.onError(e); }, noop)); + subscriptions[i] = sad; + }(idx)); + } + + var sad = new SingleAssignmentDisposable(); + sad.setDisposable(source.subscribe(function (x) { + var allValues = [x].concat(values); + if (!hasValueAll) { return; } + var res = tryCatch(resultSelector).apply(null, allValues); + if (res === errorObj) { return observer.onError(res.e); } + observer.onNext(res); + }, function (e) { observer.onError(e); }, function () { + observer.onCompleted(); + })); + subscriptions[n] = sad; + + return new CompositeDisposable(subscriptions); + }, this); + }; + + function zipArray(second, resultSelector) { + var first = this; + return new AnonymousObservable(function (o) { + var index = 0, len = second.length; + return first.subscribe(function (left) { + if (index < len) { + var right = second[index++], res = tryCatch(resultSelector)(left, right); + if (res === errorObj) { return o.onError(res.e); } + o.onNext(res); + } else { + o.onCompleted(); + } + }, function (e) { o.onError(e); }, function () { o.onCompleted(); }); + }, first); + } + + function falseFactory() { return false; } + function emptyArrayFactory() { return []; } + + /** + * Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences or an array have produced an element at a corresponding index. + * The last element in the arguments must be a function to invoke for each series of elements at corresponding indexes in the args. + * @returns {Observable} An observable sequence containing the result of combining elements of the args using the specified result selector function. + */ + observableProto.zip = function () { + if (Array.isArray(arguments[0])) { return zipArray.apply(this, arguments); } + var len = arguments.length, args = new Array(len); + for(var i = 0; i < len; i++) { args[i] = arguments[i]; } + + var parent = this, resultSelector = args.pop(); + args.unshift(parent); + return new AnonymousObservable(function (o) { + var n = args.length, + queues = arrayInitialize(n, emptyArrayFactory), + isDone = arrayInitialize(n, falseFactory); + + var subscriptions = new Array(n); + for (var idx = 0; idx < n; idx++) { + (function (i) { + var source = args[i], sad = new SingleAssignmentDisposable(); + isPromise(source) && (source = observableFromPromise(source)); + sad.setDisposable(source.subscribe(function (x) { + queues[i].push(x); + if (queues.every(function (x) { return x.length > 0; })) { + var queuedValues = queues.map(function (x) { return x.shift(); }), + res = tryCatch(resultSelector).apply(parent, queuedValues); + if (res === errorObj) { return o.onError(res.e); } + o.onNext(res); + } else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) { + o.onCompleted(); + } + }, function (e) { o.onError(e); }, function () { + isDone[i] = true; + isDone.every(identity) && o.onCompleted(); + })); + subscriptions[i] = sad; + })(idx); + } + + return new CompositeDisposable(subscriptions); + }, parent); + }; + + /** + * Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index. + * @param arguments Observable sources. + * @param {Function} resultSelector Function to invoke for each series of elements at corresponding indexes in the sources. + * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + Observable.zip = function () { + var len = arguments.length, args = new Array(len); + for(var i = 0; i < len; i++) { args[i] = arguments[i]; } + var first = args.shift(); + return first.zip.apply(first, args); + }; + + function falseFactory() { return false; } + function arrayFactory() { return []; } + + /** + * Merges the specified observable sequences into one observable sequence by emitting a list with the elements of the observable sequences at corresponding indexes. + * @param arguments Observable sources. + * @returns {Observable} An observable sequence containing lists of elements at corresponding indexes. + */ + Observable.zipArray = function () { + var sources; + if (Array.isArray(arguments[0])) { + sources = arguments[0]; + } else { + var len = arguments.length; + sources = new Array(len); + for(var i = 0; i < len; i++) { sources[i] = arguments[i]; } + } + return new AnonymousObservable(function (o) { + var n = sources.length, + queues = arrayInitialize(n, arrayFactory), + isDone = arrayInitialize(n, falseFactory); + + var subscriptions = new Array(n); + for (var idx = 0; idx < n; idx++) { + (function (i) { + subscriptions[i] = new SingleAssignmentDisposable(); + subscriptions[i].setDisposable(sources[i].subscribe(function (x) { + queues[i].push(x); + if (queues.every(function (x) { return x.length > 0; })) { + var res = queues.map(function (x) { return x.shift(); }); + o.onNext(res); + } else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) { + return o.onCompleted(); + } + }, function (e) { o.onError(e); }, function () { + isDone[i] = true; + isDone.every(identity) && o.onCompleted(); + })); + })(idx); + } + + return new CompositeDisposable(subscriptions); + }); + }; + + /** + * Hides the identity of an observable sequence. + * @returns {Observable} An observable sequence that hides the identity of the source sequence. + */ + observableProto.asObservable = function () { + var source = this; + return new AnonymousObservable(function (o) { return source.subscribe(o); }, source); + }; + + /** + * Projects each element of an observable sequence into zero or more buffers which are produced based on element count information. + * + * @example + * var res = xs.bufferWithCount(10); + * var res = xs.bufferWithCount(10, 1); + * @param {Number} count Length of each buffer. + * @param {Number} [skip] Number of elements to skip between creation of consecutive buffers. If not provided, defaults to the count. + * @returns {Observable} An observable sequence of buffers. + */ + observableProto.bufferWithCount = function (count, skip) { + if (typeof skip !== 'number') { + skip = count; + } + return this.windowWithCount(count, skip).selectMany(function (x) { + return x.toArray(); + }).where(function (x) { + return x.length > 0; + }); + }; + + /** + * Dematerializes the explicit notification values of an observable sequence as implicit notifications. + * @returns {Observable} An observable sequence exhibiting the behavior corresponding to the source sequence's notification values. + */ + observableProto.dematerialize = function () { + var source = this; + return new AnonymousObservable(function (o) { + return source.subscribe(function (x) { return x.accept(o); }, function(e) { o.onError(e); }, function () { o.onCompleted(); }); + }, this); + }; + + /** + * Returns an observable sequence that contains only distinct contiguous elements according to the keySelector and the comparer. + * + * var obs = observable.distinctUntilChanged(); + * var obs = observable.distinctUntilChanged(function (x) { return x.id; }); + * var obs = observable.distinctUntilChanged(function (x) { return x.id; }, function (x, y) { return x === y; }); + * + * @param {Function} [keySelector] A function to compute the comparison key for each element. If not provided, it projects the value. + * @param {Function} [comparer] Equality comparer for computed key values. If not provided, defaults to an equality comparer function. + * @returns {Observable} An observable sequence only containing the distinct contiguous elements, based on a computed key value, from the source sequence. + */ + observableProto.distinctUntilChanged = function (keySelector, comparer) { + var source = this; + comparer || (comparer = defaultComparer); + return new AnonymousObservable(function (o) { + var hasCurrentKey = false, currentKey; + return source.subscribe(function (value) { + var key = value; + if (keySelector) { + key = tryCatch(keySelector)(value); + if (key === errorObj) { return o.onError(key.e); } + } + if (hasCurrentKey) { + var comparerEquals = tryCatch(comparer)(currentKey, key); + if (comparerEquals === errorObj) { return o.onError(comparerEquals.e); } + } + if (!hasCurrentKey || !comparerEquals) { + hasCurrentKey = true; + currentKey = key; + o.onNext(value); + } + }, function (e) { o.onError(e); }, function () { o.onCompleted(); }); + }, this); + }; + + var TapObservable = (function(__super__) { + inherits(TapObservable,__super__); + function TapObservable(source, observerOrOnNext, onError, onCompleted) { + this.source = source; + this.t = !observerOrOnNext || isFunction(observerOrOnNext) ? + observerCreate(observerOrOnNext || noop, onError || noop, onCompleted || noop) : + observerOrOnNext; + __super__.call(this); + } + + TapObservable.prototype.subscribeCore = function(o) { + return this.source.subscribe(new InnerObserver(o, this.t)); + }; + + function InnerObserver(o, t) { + this.o = o; + this.t = t; + this.isStopped = false; + } + InnerObserver.prototype.onNext = function(x) { + if (this.isStopped) { return; } + var res = tryCatch(this.t.onNext).call(this.t, x); + if (res === errorObj) { this.o.onError(res.e); } + this.o.onNext(x); + }; + InnerObserver.prototype.onError = function(err) { + if (!this.isStopped) { + this.isStopped = true; + var res = tryCatch(this.t.onError).call(this.t, err); + if (res === errorObj) { return this.o.onError(res.e); } + this.o.onError(err); + } + }; + InnerObserver.prototype.onCompleted = function() { + if (!this.isStopped) { + this.isStopped = true; + var res = tryCatch(this.t.onCompleted).call(this.t); + if (res === errorObj) { return this.o.onError(res.e); } + this.o.onCompleted(); + } + }; + InnerObserver.prototype.dispose = function() { this.isStopped = true; }; + InnerObserver.prototype.fail = function (e) { + if (!this.isStopped) { + this.isStopped = true; + this.o.onError(e); + return true; + } + return false; + }; + + return TapObservable; + }(ObservableBase)); + + /** + * Invokes an action for each element in the observable sequence and invokes an action upon graceful or exceptional termination of the observable sequence. + * This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline. + * @param {Function | Observer} observerOrOnNext Action to invoke for each element in the observable sequence or an o. + * @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function. + * @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function. + * @returns {Observable} The source sequence with the side-effecting behavior applied. + */ + observableProto['do'] = observableProto.tap = observableProto.doAction = function (observerOrOnNext, onError, onCompleted) { + return new TapObservable(this, observerOrOnNext, onError, onCompleted); + }; + + /** + * Invokes an action for each element in the observable sequence. + * This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline. + * @param {Function} onNext Action to invoke for each element in the observable sequence. + * @param {Any} [thisArg] Object to use as this when executing callback. + * @returns {Observable} The source sequence with the side-effecting behavior applied. + */ + observableProto.doOnNext = observableProto.tapOnNext = function (onNext, thisArg) { + return this.tap(typeof thisArg !== 'undefined' ? function (x) { onNext.call(thisArg, x); } : onNext); + }; + + /** + * Invokes an action upon exceptional termination of the observable sequence. + * This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline. + * @param {Function} onError Action to invoke upon exceptional termination of the observable sequence. + * @param {Any} [thisArg] Object to use as this when executing callback. + * @returns {Observable} The source sequence with the side-effecting behavior applied. + */ + observableProto.doOnError = observableProto.tapOnError = function (onError, thisArg) { + return this.tap(noop, typeof thisArg !== 'undefined' ? function (e) { onError.call(thisArg, e); } : onError); + }; + + /** + * Invokes an action upon graceful termination of the observable sequence. + * This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline. + * @param {Function} onCompleted Action to invoke upon graceful termination of the observable sequence. + * @param {Any} [thisArg] Object to use as this when executing callback. + * @returns {Observable} The source sequence with the side-effecting behavior applied. + */ + observableProto.doOnCompleted = observableProto.tapOnCompleted = function (onCompleted, thisArg) { + return this.tap(noop, null, typeof thisArg !== 'undefined' ? function () { onCompleted.call(thisArg); } : onCompleted); + }; + + /** + * Invokes a specified action after the source observable sequence terminates gracefully or exceptionally. + * @param {Function} finallyAction Action to invoke after the source observable sequence terminates. + * @returns {Observable} Source sequence with the action-invoking termination behavior applied. + */ + observableProto['finally'] = observableProto.ensure = function (action) { + var source = this; + return new AnonymousObservable(function (observer) { + var subscription = tryCatch(source.subscribe).call(source, observer); + if (subscription === errorObj) { + action(); + return thrower(subscription.e); + } + return disposableCreate(function () { + var r = tryCatch(subscription.dispose).call(subscription); + action(); + r === errorObj && thrower(r.e); + }); + }, this); + }; + + var IgnoreElementsObservable = (function(__super__) { + inherits(IgnoreElementsObservable, __super__); + + function IgnoreElementsObservable(source) { + this.source = source; + __super__.call(this); + } + + IgnoreElementsObservable.prototype.subscribeCore = function (o) { + return this.source.subscribe(new InnerObserver(o)); + }; + + function InnerObserver(o) { + this.o = o; + this.isStopped = false; + } + InnerObserver.prototype.onNext = noop; + InnerObserver.prototype.onError = function (err) { + if(!this.isStopped) { + this.isStopped = true; + this.o.onError(err); + } + }; + InnerObserver.prototype.onCompleted = function () { + if(!this.isStopped) { + this.isStopped = true; + this.o.onCompleted(); + } + }; + InnerObserver.prototype.dispose = function() { this.isStopped = true; }; + InnerObserver.prototype.fail = function (e) { + if (!this.isStopped) { + this.isStopped = true; + this.observer.onError(e); + return true; + } + + return false; + }; + + return IgnoreElementsObservable; + }(ObservableBase)); + + /** + * Ignores all elements in an observable sequence leaving only the termination messages. + * @returns {Observable} An empty observable sequence that signals termination, successful or exceptional, of the source sequence. + */ + observableProto.ignoreElements = function () { + return new IgnoreElementsObservable(this); + }; + + /** + * Materializes the implicit notifications of an observable sequence as explicit notification values. + * @returns {Observable} An observable sequence containing the materialized notification values from the source sequence. + */ + observableProto.materialize = function () { + var source = this; + return new AnonymousObservable(function (observer) { + return source.subscribe(function (value) { + observer.onNext(notificationCreateOnNext(value)); + }, function (e) { + observer.onNext(notificationCreateOnError(e)); + observer.onCompleted(); + }, function () { + observer.onNext(notificationCreateOnCompleted()); + observer.onCompleted(); + }); + }, source); + }; + + /** + * Repeats the observable sequence a specified number of times. If the repeat count is not specified, the sequence repeats indefinitely. + * @param {Number} [repeatCount] Number of times to repeat the sequence. If not provided, repeats the sequence indefinitely. + * @returns {Observable} The observable sequence producing the elements of the given sequence repeatedly. + */ + observableProto.repeat = function (repeatCount) { + return enumerableRepeat(this, repeatCount).concat(); + }; + + /** + * Repeats the source observable sequence the specified number of times or until it successfully terminates. If the retry count is not specified, it retries indefinitely. + * Note if you encounter an error and want it to retry once, then you must use .retry(2); + * + * @example + * var res = retried = retry.repeat(); + * var res = retried = retry.repeat(2); + * @param {Number} [retryCount] Number of times to retry the sequence. If not provided, retry the sequence indefinitely. + * @returns {Observable} An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully. + */ + observableProto.retry = function (retryCount) { + return enumerableRepeat(this, retryCount).catchError(); + }; + + /** + * Repeats the source observable sequence upon error each time the notifier emits or until it successfully terminates. + * if the notifier completes, the observable sequence completes. + * + * @example + * var timer = Observable.timer(500); + * var source = observable.retryWhen(timer); + * @param {Observable} [notifier] An observable that triggers the retries or completes the observable with onNext or onCompleted respectively. + * @returns {Observable} An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully. + */ + observableProto.retryWhen = function (notifier) { + return enumerableRepeat(this).catchErrorWhen(notifier); + }; + var ScanObservable = (function(__super__) { + inherits(ScanObservable, __super__); + function ScanObservable(source, accumulator, hasSeed, seed) { + this.source = source; + this.accumulator = accumulator; + this.hasSeed = hasSeed; + this.seed = seed; + __super__.call(this); + } + + ScanObservable.prototype.subscribeCore = function(observer) { + return this.source.subscribe(new ScanObserver(observer,this)); + }; + + return ScanObservable; + }(ObservableBase)); + + function ScanObserver(observer, parent) { + this.observer = observer; + this.accumulator = parent.accumulator; + this.hasSeed = parent.hasSeed; + this.seed = parent.seed; + this.hasAccumulation = false; + this.accumulation = null; + this.hasValue = false; + this.isStopped = false; + } + ScanObserver.prototype.onNext = function (x) { + if (this.isStopped) { return; } + !this.hasValue && (this.hasValue = true); + try { + if (this.hasAccumulation) { + this.accumulation = this.accumulator(this.accumulation, x); + } else { + this.accumulation = this.hasSeed ? this.accumulator(this.seed, x) : x; + this.hasAccumulation = true; + } + } catch (e) { + return this.observer.onError(e); + } + this.observer.onNext(this.accumulation); + }; + ScanObserver.prototype.onError = function (e) { + if (!this.isStopped) { + this.isStopped = true; + this.observer.onError(e); + } + }; + ScanObserver.prototype.onCompleted = function () { + if (!this.isStopped) { + this.isStopped = true; + !this.hasValue && this.hasSeed && this.observer.onNext(this.seed); + this.observer.onCompleted(); + } + }; + ScanObserver.prototype.dispose = function() { this.isStopped = true; }; + ScanObserver.prototype.fail = function (e) { + if (!this.isStopped) { + this.isStopped = true; + this.observer.onError(e); + return true; + } + return false; + }; + + /** + * Applies an accumulator function over an observable sequence and returns each intermediate result. The optional seed value is used as the initial accumulator value. + * For aggregation behavior with no intermediate results, see Observable.aggregate. + * @param {Mixed} [seed] The initial accumulator value. + * @param {Function} accumulator An accumulator function to be invoked on each element. + * @returns {Observable} An observable sequence containing the accumulated values. + */ + observableProto.scan = function () { + var hasSeed = false, seed, accumulator, source = this; + if (arguments.length === 2) { + hasSeed = true; + seed = arguments[0]; + accumulator = arguments[1]; + } else { + accumulator = arguments[0]; + } + return new ScanObservable(this, accumulator, hasSeed, seed); + }; + + /** + * Bypasses a specified number of elements at the end of an observable sequence. + * @description + * This operator accumulates a queue with a length enough to store the first `count` elements. As more elements are + * received, elements are taken from the front of the queue and produced on the result sequence. This causes elements to be delayed. + * @param count Number of elements to bypass at the end of the source sequence. + * @returns {Observable} An observable sequence containing the source sequence elements except for the bypassed ones at the end. + */ + observableProto.skipLast = function (count) { + if (count < 0) { throw new ArgumentOutOfRangeError(); } + var source = this; + return new AnonymousObservable(function (o) { + var q = []; + return source.subscribe(function (x) { + q.push(x); + q.length > count && o.onNext(q.shift()); + }, function (e) { o.onError(e); }, function () { o.onCompleted(); }); + }, source); + }; + + /** + * Prepends a sequence of values to an observable sequence with an optional scheduler and an argument list of values to prepend. + * @example + * var res = source.startWith(1, 2, 3); + * var res = source.startWith(Rx.Scheduler.timeout, 1, 2, 3); + * @param {Arguments} args The specified values to prepend to the observable sequence + * @returns {Observable} The source sequence prepended with the specified values. + */ + observableProto.startWith = function () { + var values, scheduler, start = 0; + if (!!arguments.length && isScheduler(arguments[0])) { + scheduler = arguments[0]; + start = 1; + } else { + scheduler = immediateScheduler; + } + for(var args = [], i = start, len = arguments.length; i < len; i++) { args.push(arguments[i]); } + return enumerableOf([observableFromArray(args, scheduler), this]).concat(); + }; + + /** + * Returns a specified number of contiguous elements from the end of an observable sequence. + * @description + * This operator accumulates a buffer with a length enough to store elements count elements. Upon completion of + * the source sequence, this buffer is drained on the result sequence. This causes the elements to be delayed. + * @param {Number} count Number of elements to take from the end of the source sequence. + * @returns {Observable} An observable sequence containing the specified number of elements from the end of the source sequence. + */ + observableProto.takeLast = function (count) { + if (count < 0) { throw new ArgumentOutOfRangeError(); } + var source = this; + return new AnonymousObservable(function (o) { + var q = []; + return source.subscribe(function (x) { + q.push(x); + q.length > count && q.shift(); + }, function (e) { o.onError(e); }, function () { + while (q.length > 0) { o.onNext(q.shift()); } + o.onCompleted(); + }); + }, source); + }; + + /** + * Returns an array with the specified number of contiguous elements from the end of an observable sequence. + * + * @description + * This operator accumulates a buffer with a length enough to store count elements. Upon completion of the + * source sequence, this buffer is produced on the result sequence. + * @param {Number} count Number of elements to take from the end of the source sequence. + * @returns {Observable} An observable sequence containing a single array with the specified number of elements from the end of the source sequence. + */ + observableProto.takeLastBuffer = function (count) { + var source = this; + return new AnonymousObservable(function (o) { + var q = []; + return source.subscribe(function (x) { + q.push(x); + q.length > count && q.shift(); + }, function (e) { o.onError(e); }, function () { + o.onNext(q); + o.onCompleted(); + }); + }, source); + }; + + /** + * Projects each element of an observable sequence into zero or more windows which are produced based on element count information. + * + * var res = xs.windowWithCount(10); + * var res = xs.windowWithCount(10, 1); + * @param {Number} count Length of each window. + * @param {Number} [skip] Number of elements to skip between creation of consecutive windows. If not specified, defaults to the count. + * @returns {Observable} An observable sequence of windows. + */ + observableProto.windowWithCount = function (count, skip) { + var source = this; + +count || (count = 0); + Math.abs(count) === Infinity && (count = 0); + if (count <= 0) { throw new ArgumentOutOfRangeError(); } + skip == null && (skip = count); + +skip || (skip = 0); + Math.abs(skip) === Infinity && (skip = 0); + + if (skip <= 0) { throw new ArgumentOutOfRangeError(); } + return new AnonymousObservable(function (observer) { + var m = new SingleAssignmentDisposable(), + refCountDisposable = new RefCountDisposable(m), + n = 0, + q = []; + + function createWindow () { + var s = new Subject(); + q.push(s); + observer.onNext(addRef(s, refCountDisposable)); + } + + createWindow(); + + m.setDisposable(source.subscribe( + function (x) { + for (var i = 0, len = q.length; i < len; i++) { q[i].onNext(x); } + var c = n - count + 1; + c >= 0 && c % skip === 0 && q.shift().onCompleted(); + ++n % skip === 0 && createWindow(); + }, + function (e) { + while (q.length > 0) { q.shift().onError(e); } + observer.onError(e); + }, + function () { + while (q.length > 0) { q.shift().onCompleted(); } + observer.onCompleted(); + } + )); + return refCountDisposable; + }, source); + }; + + function concatMap(source, selector, thisArg) { + var selectorFunc = bindCallback(selector, thisArg, 3); + return source.map(function (x, i) { + var result = selectorFunc(x, i, source); + isPromise(result) && (result = observableFromPromise(result)); + (isArrayLike(result) || isIterable(result)) && (result = observableFrom(result)); + return result; + }).concatAll(); + } + + /** + * One of the Following: + * Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence. + * + * @example + * var res = source.concatMap(function (x) { return Rx.Observable.range(0, x); }); + * Or: + * Projects each element of an observable sequence to an observable sequence, invokes the result selector for the source element and each of the corresponding inner sequence's elements, and merges the results into one observable sequence. + * + * var res = source.concatMap(function (x) { return Rx.Observable.range(0, x); }, function (x, y) { return x + y; }); + * Or: + * Projects each element of the source observable sequence to the other observable sequence and merges the resulting observable sequences into one observable sequence. + * + * var res = source.concatMap(Rx.Observable.fromArray([1,2,3])); + * @param {Function} selector A transform function to apply to each element or an observable sequence to project each element from the + * source sequence onto which could be either an observable or Promise. + * @param {Function} [resultSelector] A transform function to apply to each element of the intermediate sequence. + * @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function collectionSelector on each element of the input sequence and then mapping each of those sequence elements and their corresponding source element to a result element. + */ + observableProto.selectConcat = observableProto.concatMap = function (selector, resultSelector, thisArg) { + if (isFunction(selector) && isFunction(resultSelector)) { + return this.concatMap(function (x, i) { + var selectorResult = selector(x, i); + isPromise(selectorResult) && (selectorResult = observableFromPromise(selectorResult)); + (isArrayLike(selectorResult) || isIterable(selectorResult)) && (selectorResult = observableFrom(selectorResult)); + + return selectorResult.map(function (y, i2) { + return resultSelector(x, y, i, i2); + }); + }); + } + return isFunction(selector) ? + concatMap(this, selector, thisArg) : + concatMap(this, function () { return selector; }); + }; + + /** + * Projects each notification of an observable sequence to an observable sequence and concats the resulting observable sequences into one observable sequence. + * @param {Function} onNext A transform function to apply to each element; the second parameter of the function represents the index of the source element. + * @param {Function} onError A transform function to apply when an error occurs in the source sequence. + * @param {Function} onCompleted A transform function to apply when the end of the source sequence is reached. + * @param {Any} [thisArg] An optional "this" to use to invoke each transform. + * @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function corresponding to each notification in the input sequence. + */ + observableProto.concatMapObserver = observableProto.selectConcatObserver = function(onNext, onError, onCompleted, thisArg) { + var source = this, + onNextFunc = bindCallback(onNext, thisArg, 2), + onErrorFunc = bindCallback(onError, thisArg, 1), + onCompletedFunc = bindCallback(onCompleted, thisArg, 0); + return new AnonymousObservable(function (observer) { + var index = 0; + return source.subscribe( + function (x) { + var result; + try { + result = onNextFunc(x, index++); + } catch (e) { + observer.onError(e); + return; + } + isPromise(result) && (result = observableFromPromise(result)); + observer.onNext(result); + }, + function (err) { + var result; + try { + result = onErrorFunc(err); + } catch (e) { + observer.onError(e); + return; + } + isPromise(result) && (result = observableFromPromise(result)); + observer.onNext(result); + observer.onCompleted(); + }, + function () { + var result; + try { + result = onCompletedFunc(); + } catch (e) { + observer.onError(e); + return; + } + isPromise(result) && (result = observableFromPromise(result)); + observer.onNext(result); + observer.onCompleted(); + }); + }, this).concatAll(); + }; + + /** + * Returns the elements of the specified sequence or the specified value in a singleton sequence if the sequence is empty. + * + * var res = obs = xs.defaultIfEmpty(); + * 2 - obs = xs.defaultIfEmpty(false); + * + * @memberOf Observable# + * @param defaultValue The value to return if the sequence is empty. If not provided, this defaults to null. + * @returns {Observable} An observable sequence that contains the specified default value if the source is empty; otherwise, the elements of the source itself. + */ + observableProto.defaultIfEmpty = function (defaultValue) { + var source = this; + defaultValue === undefined && (defaultValue = null); + return new AnonymousObservable(function (observer) { + var found = false; + return source.subscribe(function (x) { + found = true; + observer.onNext(x); + }, + function (e) { observer.onError(e); }, + function () { + !found && observer.onNext(defaultValue); + observer.onCompleted(); + }); + }, source); + }; + + // Swap out for Array.findIndex + function arrayIndexOfComparer(array, item, comparer) { + for (var i = 0, len = array.length; i < len; i++) { + if (comparer(array[i], item)) { return i; } + } + return -1; + } + + function HashSet(comparer) { + this.comparer = comparer; + this.set = []; + } + HashSet.prototype.push = function(value) { + var retValue = arrayIndexOfComparer(this.set, value, this.comparer) === -1; + retValue && this.set.push(value); + return retValue; + }; + + /** + * Returns an observable sequence that contains only distinct elements according to the keySelector and the comparer. + * Usage of this operator should be considered carefully due to the maintenance of an internal lookup structure which can grow large. + * + * @example + * var res = obs = xs.distinct(); + * 2 - obs = xs.distinct(function (x) { return x.id; }); + * 2 - obs = xs.distinct(function (x) { return x.id; }, function (a,b) { return a === b; }); + * @param {Function} [keySelector] A function to compute the comparison key for each element. + * @param {Function} [comparer] Used to compare items in the collection. + * @returns {Observable} An observable sequence only containing the distinct elements, based on a computed key value, from the source sequence. + */ + observableProto.distinct = function (keySelector, comparer) { + var source = this; + comparer || (comparer = defaultComparer); + return new AnonymousObservable(function (o) { + var hashSet = new HashSet(comparer); + return source.subscribe(function (x) { + var key = x; + + if (keySelector) { + try { + key = keySelector(x); + } catch (e) { + o.onError(e); + return; + } + } + hashSet.push(key) && o.onNext(x); + }, + function (e) { o.onError(e); }, function () { o.onCompleted(); }); + }, this); + }; + + /** + * Groups the elements of an observable sequence according to a specified key selector function and comparer and selects the resulting elements by using a specified function. + * + * @example + * var res = observable.groupBy(function (x) { return x.id; }); + * 2 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }); + * 3 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }, function (x) { return x.toString(); }); + * @param {Function} keySelector A function to extract the key for each element. + * @param {Function} [elementSelector] A function to map each source element to an element in an observable group. + * @param {Function} [comparer] Used to determine whether the objects are equal. + * @returns {Observable} A sequence of observable groups, each of which corresponds to a unique key value, containing all elements that share that same key value. + */ + observableProto.groupBy = function (keySelector, elementSelector, comparer) { + return this.groupByUntil(keySelector, elementSelector, observableNever, comparer); + }; + + /** + * Groups the elements of an observable sequence according to a specified key selector function. + * A duration selector function is used to control the lifetime of groups. When a group expires, it receives an OnCompleted notification. When a new element with the same + * key value as a reclaimed group occurs, the group will be reborn with a new lifetime request. + * + * @example + * var res = observable.groupByUntil(function (x) { return x.id; }, null, function () { return Rx.Observable.never(); }); + * 2 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }, function () { return Rx.Observable.never(); }); + * 3 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }, function () { return Rx.Observable.never(); }, function (x) { return x.toString(); }); + * @param {Function} keySelector A function to extract the key for each element. + * @param {Function} durationSelector A function to signal the expiration of a group. + * @param {Function} [comparer] Used to compare objects. When not specified, the default comparer is used. + * @returns {Observable} + * A sequence of observable groups, each of which corresponds to a unique key value, containing all elements that share that same key value. + * If a group's lifetime expires, a new group with the same key value can be created once an element with such a key value is encoutered. + * + */ + observableProto.groupByUntil = function (keySelector, elementSelector, durationSelector, comparer) { + var source = this; + elementSelector || (elementSelector = identity); + comparer || (comparer = defaultComparer); + return new AnonymousObservable(function (observer) { + function handleError(e) { return function (item) { item.onError(e); }; } + var map = new Dictionary(0, comparer), + groupDisposable = new CompositeDisposable(), + refCountDisposable = new RefCountDisposable(groupDisposable); + + groupDisposable.add(source.subscribe(function (x) { + var key; + try { + key = keySelector(x); + } catch (e) { + map.getValues().forEach(handleError(e)); + observer.onError(e); + return; + } + + var fireNewMapEntry = false, + writer = map.tryGetValue(key); + if (!writer) { + writer = new Subject(); + map.set(key, writer); + fireNewMapEntry = true; + } + + if (fireNewMapEntry) { + var group = new GroupedObservable(key, writer, refCountDisposable), + durationGroup = new GroupedObservable(key, writer); + try { + duration = durationSelector(durationGroup); + } catch (e) { + map.getValues().forEach(handleError(e)); + observer.onError(e); + return; + } + + observer.onNext(group); + + var md = new SingleAssignmentDisposable(); + groupDisposable.add(md); + + var expire = function () { + map.remove(key) && writer.onCompleted(); + groupDisposable.remove(md); + }; + + md.setDisposable(duration.take(1).subscribe( + noop, + function (exn) { + map.getValues().forEach(handleError(exn)); + observer.onError(exn); + }, + expire) + ); + } + + var element; + try { + element = elementSelector(x); + } catch (e) { + map.getValues().forEach(handleError(e)); + observer.onError(e); + return; + } + + writer.onNext(element); + }, function (ex) { + map.getValues().forEach(handleError(ex)); + observer.onError(ex); + }, function () { + map.getValues().forEach(function (item) { item.onCompleted(); }); + observer.onCompleted(); + })); + + return refCountDisposable; + }, source); + }; + + var MapObservable = (function (__super__) { + inherits(MapObservable, __super__); + + function MapObservable(source, selector, thisArg) { + this.source = source; + this.selector = bindCallback(selector, thisArg, 3); + __super__.call(this); + } + + function innerMap(selector, self) { + return function (x, i, o) { return selector.call(this, self.selector(x, i, o), i, o); } + } + + MapObservable.prototype.internalMap = function (selector, thisArg) { + return new MapObservable(this.source, innerMap(selector, this), thisArg); + }; + + MapObservable.prototype.subscribeCore = function (o) { + return this.source.subscribe(new InnerObserver(o, this.selector, this)); + }; + + function InnerObserver(o, selector, source) { + this.o = o; + this.selector = selector; + this.source = source; + this.i = 0; + this.isStopped = false; + } + + InnerObserver.prototype.onNext = function(x) { + if (this.isStopped) { return; } + var result = tryCatch(this.selector)(x, this.i++, this.source); + if (result === errorObj) { + return this.o.onError(result.e); + } + this.o.onNext(result); + }; + InnerObserver.prototype.onError = function (e) { + if(!this.isStopped) { this.isStopped = true; this.o.onError(e); } + }; + InnerObserver.prototype.onCompleted = function () { + if(!this.isStopped) { this.isStopped = true; this.o.onCompleted(); } + }; + InnerObserver.prototype.dispose = function() { this.isStopped = true; }; + InnerObserver.prototype.fail = function (e) { + if (!this.isStopped) { + this.isStopped = true; + this.o.onError(e); + return true; + } + + return false; + }; + + return MapObservable; + + }(ObservableBase)); + + /** + * Projects each element of an observable sequence into a new form by incorporating the element's index. + * @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element. + * @param {Any} [thisArg] Object to use as this when executing callback. + * @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source. + */ + observableProto.map = observableProto.select = function (selector, thisArg) { + var selectorFn = typeof selector === 'function' ? selector : function () { return selector; }; + return this instanceof MapObservable ? + this.internalMap(selectorFn, thisArg) : + new MapObservable(this, selectorFn, thisArg); + }; + + /** + * Retrieves the value of a specified nested property from all elements in + * the Observable sequence. + * @param {Arguments} arguments The nested properties to pluck. + * @returns {Observable} Returns a new Observable sequence of property values. + */ + observableProto.pluck = function () { + var args = arguments, len = arguments.length; + if (len === 0) { throw new Error('List of properties cannot be empty.'); } + return this.map(function (x) { + var currentProp = x; + for (var i = 0; i < len; i++) { + var p = currentProp[args[i]]; + if (typeof p !== 'undefined') { + currentProp = p; + } else { + return undefined; + } + } + return currentProp; + }); + }; + + function flatMap(source, selector, thisArg) { + var selectorFunc = bindCallback(selector, thisArg, 3); + return source.map(function (x, i) { + var result = selectorFunc(x, i, source); + isPromise(result) && (result = observableFromPromise(result)); + (isArrayLike(result) || isIterable(result)) && (result = observableFrom(result)); + return result; + }).mergeAll(); + } + + /** + * One of the Following: + * Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence. + * + * @example + * var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); }); + * Or: + * Projects each element of an observable sequence to an observable sequence, invokes the result selector for the source element and each of the corresponding inner sequence's elements, and merges the results into one observable sequence. + * + * var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); }, function (x, y) { return x + y; }); + * Or: + * Projects each element of the source observable sequence to the other observable sequence and merges the resulting observable sequences into one observable sequence. + * + * var res = source.selectMany(Rx.Observable.fromArray([1,2,3])); + * @param {Function} selector A transform function to apply to each element or an observable sequence to project each element from the source sequence onto which could be either an observable or Promise. + * @param {Function} [resultSelector] A transform function to apply to each element of the intermediate sequence. + * @param {Any} [thisArg] Object to use as this when executing callback. + * @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function collectionSelector on each element of the input sequence and then mapping each of those sequence elements and their corresponding source element to a result element. + */ + observableProto.selectMany = observableProto.flatMap = function (selector, resultSelector, thisArg) { + if (isFunction(selector) && isFunction(resultSelector)) { + return this.flatMap(function (x, i) { + var selectorResult = selector(x, i); + isPromise(selectorResult) && (selectorResult = observableFromPromise(selectorResult)); + (isArrayLike(selectorResult) || isIterable(selectorResult)) && (selectorResult = observableFrom(selectorResult)); + + return selectorResult.map(function (y, i2) { + return resultSelector(x, y, i, i2); + }); + }, thisArg); + } + return isFunction(selector) ? + flatMap(this, selector, thisArg) : + flatMap(this, function () { return selector; }); + }; + + /** + * Projects each notification of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence. + * @param {Function} onNext A transform function to apply to each element; the second parameter of the function represents the index of the source element. + * @param {Function} onError A transform function to apply when an error occurs in the source sequence. + * @param {Function} onCompleted A transform function to apply when the end of the source sequence is reached. + * @param {Any} [thisArg] An optional "this" to use to invoke each transform. + * @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function corresponding to each notification in the input sequence. + */ + observableProto.flatMapObserver = observableProto.selectManyObserver = function (onNext, onError, onCompleted, thisArg) { + var source = this; + return new AnonymousObservable(function (observer) { + var index = 0; + + return source.subscribe( + function (x) { + var result; + try { + result = onNext.call(thisArg, x, index++); + } catch (e) { + observer.onError(e); + return; + } + isPromise(result) && (result = observableFromPromise(result)); + observer.onNext(result); + }, + function (err) { + var result; + try { + result = onError.call(thisArg, err); + } catch (e) { + observer.onError(e); + return; + } + isPromise(result) && (result = observableFromPromise(result)); + observer.onNext(result); + observer.onCompleted(); + }, + function () { + var result; + try { + result = onCompleted.call(thisArg); + } catch (e) { + observer.onError(e); + return; + } + isPromise(result) && (result = observableFromPromise(result)); + observer.onNext(result); + observer.onCompleted(); + }); + }, source).mergeAll(); + }; + + /** + * Projects each element of an observable sequence into a new sequence of observable sequences by incorporating the element's index and then + * transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence. + * @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element. + * @param {Any} [thisArg] Object to use as this when executing callback. + * @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source producing an Observable of Observable sequences + * and that at any point in time produces the elements of the most recent inner observable sequence that has been received. + */ + observableProto.selectSwitch = observableProto.flatMapLatest = observableProto.switchMap = function (selector, thisArg) { + return this.select(selector, thisArg).switchLatest(); + }; + + var SkipObservable = (function(__super__) { + inherits(SkipObservable, __super__); + function SkipObservable(source, count) { + this.source = source; + this.skipCount = count; + __super__.call(this); + } + + SkipObservable.prototype.subscribeCore = function (o) { + return this.source.subscribe(new InnerObserver(o, this.skipCount)); + }; + + function InnerObserver(o, c) { + this.c = c; + this.r = c; + this.o = o; + this.isStopped = false; + } + InnerObserver.prototype.onNext = function (x) { + if (this.isStopped) { return; } + if (this.r <= 0) { + this.o.onNext(x); + } else { + this.r--; + } + }; + InnerObserver.prototype.onError = function(e) { + if (!this.isStopped) { this.isStopped = true; this.o.onError(e); } + }; + InnerObserver.prototype.onCompleted = function() { + if (!this.isStopped) { this.isStopped = true; this.o.onCompleted(); } + }; + InnerObserver.prototype.dispose = function() { this.isStopped = true; }; + InnerObserver.prototype.fail = function(e) { + if (!this.isStopped) { + this.isStopped = true; + this.o.onError(e); + return true; + } + return false; + }; + + return SkipObservable; + }(ObservableBase)); + + /** + * Bypasses a specified number of elements in an observable sequence and then returns the remaining elements. + * @param {Number} count The number of elements to skip before returning the remaining elements. + * @returns {Observable} An observable sequence that contains the elements that occur after the specified index in the input sequence. + */ + observableProto.skip = function (count) { + if (count < 0) { throw new ArgumentOutOfRangeError(); } + return new SkipObservable(this, count); + }; + /** + * Bypasses elements in an observable sequence as long as a specified condition is true and then returns the remaining elements. + * The element's index is used in the logic of the predicate function. + * + * var res = source.skipWhile(function (value) { return value < 10; }); + * var res = source.skipWhile(function (value, index) { return value < 10 || index < 10; }); + * @param {Function} predicate A function to test each element for a condition; the second parameter of the function represents the index of the source element. + * @param {Any} [thisArg] Object to use as this when executing callback. + * @returns {Observable} An observable sequence that contains the elements from the input sequence starting at the first element in the linear series that does not pass the test specified by predicate. + */ + observableProto.skipWhile = function (predicate, thisArg) { + var source = this, + callback = bindCallback(predicate, thisArg, 3); + return new AnonymousObservable(function (o) { + var i = 0, running = false; + return source.subscribe(function (x) { + if (!running) { + try { + running = !callback(x, i++, source); + } catch (e) { + o.onError(e); + return; + } + } + running && o.onNext(x); + }, function (e) { o.onError(e); }, function () { o.onCompleted(); }); + }, source); + }; + + /** + * Returns a specified number of contiguous elements from the start of an observable sequence, using the specified scheduler for the edge case of take(0). + * + * var res = source.take(5); + * var res = source.take(0, Rx.Scheduler.timeout); + * @param {Number} count The number of elements to return. + * @param {Scheduler} [scheduler] Scheduler used to produce an OnCompleted message in case 0; }, + /** + * Notifies all subscribed observers about the end of the sequence. + */ + onCompleted: function () { + checkDisposed(this); + if (this.isStopped) { return; } + this.isStopped = true; + for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) { + os[i].onCompleted(); + } + + this.observers.length = 0; + }, + /** + * Notifies all subscribed observers about the exception. + * @param {Mixed} error The exception to send to all observers. + */ + onError: function (error) { + checkDisposed(this); + if (this.isStopped) { return; } + this.isStopped = true; + this.hasError = true; + this.error = error; + + for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) { + os[i].onError(error); + } + + this.observers.length = 0; + }, + /** + * Notifies all subscribed observers about the arrival of the specified element in the sequence. + * @param {Mixed} value The value to send to all observers. + */ + onNext: function (value) { + checkDisposed(this); + if (this.isStopped) { return; } + this.value = value; + for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) { + os[i].onNext(value); + } + }, + /** + * Unsubscribe all observers and release resources. + */ + dispose: function () { + this.isDisposed = true; + this.observers = null; + this.value = null; + this.exception = null; + } + }); + + return BehaviorSubject; + }(Observable)); + + /** + * Represents an object that is both an observable sequence as well as an observer. + * Each notification is broadcasted to all subscribed and future observers, subject to buffer trimming policies. + */ + var ReplaySubject = Rx.ReplaySubject = (function (__super__) { + + var maxSafeInteger = Math.pow(2, 53) - 1; + + function createRemovableDisposable(subject, observer) { + return disposableCreate(function () { + observer.dispose(); + !subject.isDisposed && subject.observers.splice(subject.observers.indexOf(observer), 1); + }); + } + + function subscribe(observer) { + var so = new ScheduledObserver(this.scheduler, observer), + subscription = createRemovableDisposable(this, so); + checkDisposed(this); + this._trim(this.scheduler.now()); + this.observers.push(so); + + for (var i = 0, len = this.q.length; i < len; i++) { + so.onNext(this.q[i].value); + } + + if (this.hasError) { + so.onError(this.error); + } else if (this.isStopped) { + so.onCompleted(); + } + + so.ensureActive(); + return subscription; + } + + inherits(ReplaySubject, __super__); + + /** + * Initializes a new instance of the ReplaySubject class with the specified buffer size, window size and scheduler. + * @param {Number} [bufferSize] Maximum element count of the replay buffer. + * @param {Number} [windowSize] Maximum time length of the replay buffer. + * @param {Scheduler} [scheduler] Scheduler the observers are invoked on. + */ + function ReplaySubject(bufferSize, windowSize, scheduler) { + this.bufferSize = bufferSize == null ? maxSafeInteger : bufferSize; + this.windowSize = windowSize == null ? maxSafeInteger : windowSize; + this.scheduler = scheduler || currentThreadScheduler; + this.q = []; + this.observers = []; + this.isStopped = false; + this.isDisposed = false; + this.hasError = false; + this.error = null; + __super__.call(this, subscribe); + } + + addProperties(ReplaySubject.prototype, Observer.prototype, { + /** + * Indicates whether the subject has observers subscribed to it. + * @returns {Boolean} Indicates whether the subject has observers subscribed to it. + */ + hasObservers: function () { + return this.observers.length > 0; + }, + _trim: function (now) { + while (this.q.length > this.bufferSize) { + this.q.shift(); + } + while (this.q.length > 0 && (now - this.q[0].interval) > this.windowSize) { + this.q.shift(); + } + }, + /** + * Notifies all subscribed observers about the arrival of the specified element in the sequence. + * @param {Mixed} value The value to send to all observers. + */ + onNext: function (value) { + checkDisposed(this); + if (this.isStopped) { return; } + var now = this.scheduler.now(); + this.q.push({ interval: now, value: value }); + this._trim(now); + + for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) { + var observer = os[i]; + observer.onNext(value); + observer.ensureActive(); + } + }, + /** + * Notifies all subscribed observers about the exception. + * @param {Mixed} error The exception to send to all observers. + */ + onError: function (error) { + checkDisposed(this); + if (this.isStopped) { return; } + this.isStopped = true; + this.error = error; + this.hasError = true; + var now = this.scheduler.now(); + this._trim(now); + for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) { + var observer = os[i]; + observer.onError(error); + observer.ensureActive(); + } + this.observers.length = 0; + }, + /** + * Notifies all subscribed observers about the end of the sequence. + */ + onCompleted: function () { + checkDisposed(this); + if (this.isStopped) { return; } + this.isStopped = true; + var now = this.scheduler.now(); + this._trim(now); + for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) { + var observer = os[i]; + observer.onCompleted(); + observer.ensureActive(); + } + this.observers.length = 0; + }, + /** + * Unsubscribe all observers and release resources. + */ + dispose: function () { + this.isDisposed = true; + this.observers = null; + } + }); + + return ReplaySubject; + }(Observable)); + + var ConnectableObservable = Rx.ConnectableObservable = (function (__super__) { + inherits(ConnectableObservable, __super__); + + function ConnectableObservable(source, subject) { + var hasSubscription = false, + subscription, + sourceObservable = source.asObservable(); + + this.connect = function () { + if (!hasSubscription) { + hasSubscription = true; + subscription = new CompositeDisposable(sourceObservable.subscribe(subject), disposableCreate(function () { + hasSubscription = false; + })); + } + return subscription; + }; + + __super__.call(this, function (o) { return subject.subscribe(o); }); + } + + ConnectableObservable.prototype.refCount = function () { + var connectableSubscription, count = 0, source = this; + return new AnonymousObservable(function (observer) { + var shouldConnect = ++count === 1, + subscription = source.subscribe(observer); + shouldConnect && (connectableSubscription = source.connect()); + return function () { + subscription.dispose(); + --count === 0 && connectableSubscription.dispose(); + }; + }); + }; + + return ConnectableObservable; + }(Observable)); + + /** + * Returns an observable sequence that shares a single subscription to the underlying sequence. This observable sequence + * can be resubscribed to, even if all prior subscriptions have ended. (unlike `.publish().refCount()`) + * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source. + */ + observableProto.singleInstance = function() { + var source = this, hasObservable = false, observable; + + function getObservable() { + if (!hasObservable) { + hasObservable = true; + observable = source.finally(function() { hasObservable = false; }).publish().refCount(); + } + return observable; + }; + + return new AnonymousObservable(function(o) { + return getObservable().subscribe(o); + }); + }; + + var Dictionary = (function () { + + var primes = [1, 3, 7, 13, 31, 61, 127, 251, 509, 1021, 2039, 4093, 8191, 16381, 32749, 65521, 131071, 262139, 524287, 1048573, 2097143, 4194301, 8388593, 16777213, 33554393, 67108859, 134217689, 268435399, 536870909, 1073741789, 2147483647], + noSuchkey = "no such key", + duplicatekey = "duplicate key"; + + function isPrime(candidate) { + if ((candidate & 1) === 0) { return candidate === 2; } + var num1 = Math.sqrt(candidate), + num2 = 3; + while (num2 <= num1) { + if (candidate % num2 === 0) { return false; } + num2 += 2; + } + return true; + } + + function getPrime(min) { + var index, num, candidate; + for (index = 0; index < primes.length; ++index) { + num = primes[index]; + if (num >= min) { return num; } + } + candidate = min | 1; + while (candidate < primes[primes.length - 1]) { + if (isPrime(candidate)) { return candidate; } + candidate += 2; + } + return min; + } + + function stringHashFn(str) { + var hash = 757602046; + if (!str.length) { return hash; } + for (var i = 0, len = str.length; i < len; i++) { + var character = str.charCodeAt(i); + hash = ((hash << 5) - hash) + character; + hash = hash & hash; + } + return hash; + } + + function numberHashFn(key) { + var c2 = 0x27d4eb2d; + key = (key ^ 61) ^ (key >>> 16); + key = key + (key << 3); + key = key ^ (key >>> 4); + key = key * c2; + key = key ^ (key >>> 15); + return key; + } + + var getHashCode = (function () { + var uniqueIdCounter = 0; + + return function (obj) { + if (obj == null) { throw new Error(noSuchkey); } + + // Check for built-ins before tacking on our own for any object + if (typeof obj === 'string') { return stringHashFn(obj); } + if (typeof obj === 'number') { return numberHashFn(obj); } + if (typeof obj === 'boolean') { return obj === true ? 1 : 0; } + if (obj instanceof Date) { return numberHashFn(obj.valueOf()); } + if (obj instanceof RegExp) { return stringHashFn(obj.toString()); } + if (typeof obj.valueOf === 'function') { + // Hack check for valueOf + var valueOf = obj.valueOf(); + if (typeof valueOf === 'number') { return numberHashFn(valueOf); } + if (typeof valueOf === 'string') { return stringHashFn(valueOf); } + } + if (obj.hashCode) { return obj.hashCode(); } + + var id = 17 * uniqueIdCounter++; + obj.hashCode = function () { return id; }; + return id; + }; + }()); + + function newEntry() { + return { key: null, value: null, next: 0, hashCode: 0 }; + } + + function Dictionary(capacity, comparer) { + if (capacity < 0) { throw new ArgumentOutOfRangeError(); } + if (capacity > 0) { this._initialize(capacity); } + + this.comparer = comparer || defaultComparer; + this.freeCount = 0; + this.size = 0; + this.freeList = -1; + } + + var dictionaryProto = Dictionary.prototype; + + dictionaryProto._initialize = function (capacity) { + var prime = getPrime(capacity), i; + this.buckets = new Array(prime); + this.entries = new Array(prime); + for (i = 0; i < prime; i++) { + this.buckets[i] = -1; + this.entries[i] = newEntry(); + } + this.freeList = -1; + }; + + dictionaryProto.add = function (key, value) { + this._insert(key, value, true); + }; + + dictionaryProto._insert = function (key, value, add) { + if (!this.buckets) { this._initialize(0); } + var index3, + num = getHashCode(key) & 2147483647, + index1 = num % this.buckets.length; + for (var index2 = this.buckets[index1]; index2 >= 0; index2 = this.entries[index2].next) { + if (this.entries[index2].hashCode === num && this.comparer(this.entries[index2].key, key)) { + if (add) { throw new Error(duplicatekey); } + this.entries[index2].value = value; + return; + } + } + if (this.freeCount > 0) { + index3 = this.freeList; + this.freeList = this.entries[index3].next; + --this.freeCount; + } else { + if (this.size === this.entries.length) { + this._resize(); + index1 = num % this.buckets.length; + } + index3 = this.size; + ++this.size; + } + this.entries[index3].hashCode = num; + this.entries[index3].next = this.buckets[index1]; + this.entries[index3].key = key; + this.entries[index3].value = value; + this.buckets[index1] = index3; + }; + + dictionaryProto._resize = function () { + var prime = getPrime(this.size * 2), + numArray = new Array(prime); + for (index = 0; index < numArray.length; ++index) { numArray[index] = -1; } + var entryArray = new Array(prime); + for (index = 0; index < this.size; ++index) { entryArray[index] = this.entries[index]; } + for (var index = this.size; index < prime; ++index) { entryArray[index] = newEntry(); } + for (var index1 = 0; index1 < this.size; ++index1) { + var index2 = entryArray[index1].hashCode % prime; + entryArray[index1].next = numArray[index2]; + numArray[index2] = index1; + } + this.buckets = numArray; + this.entries = entryArray; + }; + + dictionaryProto.remove = function (key) { + if (this.buckets) { + var num = getHashCode(key) & 2147483647, + index1 = num % this.buckets.length, + index2 = -1; + for (var index3 = this.buckets[index1]; index3 >= 0; index3 = this.entries[index3].next) { + if (this.entries[index3].hashCode === num && this.comparer(this.entries[index3].key, key)) { + if (index2 < 0) { + this.buckets[index1] = this.entries[index3].next; + } else { + this.entries[index2].next = this.entries[index3].next; + } + this.entries[index3].hashCode = -1; + this.entries[index3].next = this.freeList; + this.entries[index3].key = null; + this.entries[index3].value = null; + this.freeList = index3; + ++this.freeCount; + return true; + } else { + index2 = index3; + } + } + } + return false; + }; + + dictionaryProto.clear = function () { + var index, len; + if (this.size <= 0) { return; } + for (index = 0, len = this.buckets.length; index < len; ++index) { + this.buckets[index] = -1; + } + for (index = 0; index < this.size; ++index) { + this.entries[index] = newEntry(); + } + this.freeList = -1; + this.size = 0; + }; + + dictionaryProto._findEntry = function (key) { + if (this.buckets) { + var num = getHashCode(key) & 2147483647; + for (var index = this.buckets[num % this.buckets.length]; index >= 0; index = this.entries[index].next) { + if (this.entries[index].hashCode === num && this.comparer(this.entries[index].key, key)) { + return index; + } + } + } + return -1; + }; + + dictionaryProto.count = function () { + return this.size - this.freeCount; + }; + + dictionaryProto.tryGetValue = function (key) { + var entry = this._findEntry(key); + return entry >= 0 ? + this.entries[entry].value : + undefined; + }; + + dictionaryProto.getValues = function () { + var index = 0, results = []; + if (this.entries) { + for (var index1 = 0; index1 < this.size; index1++) { + if (this.entries[index1].hashCode >= 0) { + results[index++] = this.entries[index1].value; + } + } + } + return results; + }; + + dictionaryProto.get = function (key) { + var entry = this._findEntry(key); + if (entry >= 0) { return this.entries[entry].value; } + throw new Error(noSuchkey); + }; + + dictionaryProto.set = function (key, value) { + this._insert(key, value, false); + }; + + dictionaryProto.containskey = function (key) { + return this._findEntry(key) >= 0; + }; + + return Dictionary; + }()); + + /** + * Correlates the elements of two sequences based on overlapping durations. + * + * @param {Observable} right The right observable sequence to join elements for. + * @param {Function} leftDurationSelector A function to select the duration (expressed as an observable sequence) of each element of the left observable sequence, used to determine overlap. + * @param {Function} rightDurationSelector A function to select the duration (expressed as an observable sequence) of each element of the right observable sequence, used to determine overlap. + * @param {Function} resultSelector A function invoked to compute a result element for any two overlapping elements of the left and right observable sequences. The parameters passed to the function correspond with the elements from the left and right source sequences for which overlap occurs. + * @returns {Observable} An observable sequence that contains result elements computed from source elements that have an overlapping duration. + */ + observableProto.join = function (right, leftDurationSelector, rightDurationSelector, resultSelector) { + var left = this; + return new AnonymousObservable(function (observer) { + var group = new CompositeDisposable(); + var leftDone = false, rightDone = false; + var leftId = 0, rightId = 0; + var leftMap = new Dictionary(), rightMap = new Dictionary(); + + group.add(left.subscribe( + function (value) { + var id = leftId++; + var md = new SingleAssignmentDisposable(); + + leftMap.add(id, value); + group.add(md); + + var expire = function () { + leftMap.remove(id) && leftMap.count() === 0 && leftDone && observer.onCompleted(); + group.remove(md); + }; + + var duration; + try { + duration = leftDurationSelector(value); + } catch (e) { + observer.onError(e); + return; + } + + md.setDisposable(duration.take(1).subscribe(noop, observer.onError.bind(observer), expire)); + + rightMap.getValues().forEach(function (v) { + var result; + try { + result = resultSelector(value, v); + } catch (exn) { + observer.onError(exn); + return; + } + + observer.onNext(result); + }); + }, + observer.onError.bind(observer), + function () { + leftDone = true; + (rightDone || leftMap.count() === 0) && observer.onCompleted(); + }) + ); + + group.add(right.subscribe( + function (value) { + var id = rightId++; + var md = new SingleAssignmentDisposable(); + + rightMap.add(id, value); + group.add(md); + + var expire = function () { + rightMap.remove(id) && rightMap.count() === 0 && rightDone && observer.onCompleted(); + group.remove(md); + }; + + var duration; + try { + duration = rightDurationSelector(value); + } catch (e) { + observer.onError(e); + return; + } + + md.setDisposable(duration.take(1).subscribe(noop, observer.onError.bind(observer), expire)); + + leftMap.getValues().forEach(function (v) { + var result; + try { + result = resultSelector(v, value); + } catch (exn) { + observer.onError(exn); + return; + } + + observer.onNext(result); + }); + }, + observer.onError.bind(observer), + function () { + rightDone = true; + (leftDone || rightMap.count() === 0) && observer.onCompleted(); + }) + ); + return group; + }, left); + }; + + /** + * Correlates the elements of two sequences based on overlapping durations, and groups the results. + * + * @param {Observable} right The right observable sequence to join elements for. + * @param {Function} leftDurationSelector A function to select the duration (expressed as an observable sequence) of each element of the left observable sequence, used to determine overlap. + * @param {Function} rightDurationSelector A function to select the duration (expressed as an observable sequence) of each element of the right observable sequence, used to determine overlap. + * @param {Function} resultSelector A function invoked to compute a result element for any element of the left sequence with overlapping elements from the right observable sequence. The first parameter passed to the function is an element of the left sequence. The second parameter passed to the function is an observable sequence with elements from the right sequence that overlap with the left sequence's element. + * @returns {Observable} An observable sequence that contains result elements computed from source elements that have an overlapping duration. + */ + observableProto.groupJoin = function (right, leftDurationSelector, rightDurationSelector, resultSelector) { + var left = this; + return new AnonymousObservable(function (observer) { + var group = new CompositeDisposable(); + var r = new RefCountDisposable(group); + var leftMap = new Dictionary(), rightMap = new Dictionary(); + var leftId = 0, rightId = 0; + + function handleError(e) { return function (v) { v.onError(e); }; }; + + group.add(left.subscribe( + function (value) { + var s = new Subject(); + var id = leftId++; + leftMap.add(id, s); + + var result; + try { + result = resultSelector(value, addRef(s, r)); + } catch (e) { + leftMap.getValues().forEach(handleError(e)); + observer.onError(e); + return; + } + observer.onNext(result); + + rightMap.getValues().forEach(function (v) { s.onNext(v); }); + + var md = new SingleAssignmentDisposable(); + group.add(md); + + var expire = function () { + leftMap.remove(id) && s.onCompleted(); + group.remove(md); + }; + + var duration; + try { + duration = leftDurationSelector(value); + } catch (e) { + leftMap.getValues().forEach(handleError(e)); + observer.onError(e); + return; + } + + md.setDisposable(duration.take(1).subscribe( + noop, + function (e) { + leftMap.getValues().forEach(handleError(e)); + observer.onError(e); + }, + expire) + ); + }, + function (e) { + leftMap.getValues().forEach(handleError(e)); + observer.onError(e); + }, + observer.onCompleted.bind(observer)) + ); + + group.add(right.subscribe( + function (value) { + var id = rightId++; + rightMap.add(id, value); + + var md = new SingleAssignmentDisposable(); + group.add(md); + + var expire = function () { + rightMap.remove(id); + group.remove(md); + }; + + var duration; + try { + duration = rightDurationSelector(value); + } catch (e) { + leftMap.getValues().forEach(handleError(e)); + observer.onError(e); + return; + } + md.setDisposable(duration.take(1).subscribe( + noop, + function (e) { + leftMap.getValues().forEach(handleError(e)); + observer.onError(e); + }, + expire) + ); + + leftMap.getValues().forEach(function (v) { v.onNext(value); }); + }, + function (e) { + leftMap.getValues().forEach(handleError(e)); + observer.onError(e); + }) + ); + + return r; + }, left); + }; + + /** + * Projects each element of an observable sequence into zero or more buffers. + * + * @param {Mixed} bufferOpeningsOrClosingSelector Observable sequence whose elements denote the creation of new windows, or, a function invoked to define the boundaries of the produced windows (a new window is started when the previous one is closed, resulting in non-overlapping windows). + * @param {Function} [bufferClosingSelector] A function invoked to define the closing of each produced window. If a closing selector function is specified for the first parameter, this parameter is ignored. + * @returns {Observable} An observable sequence of windows. + */ + observableProto.buffer = function (bufferOpeningsOrClosingSelector, bufferClosingSelector) { + return this.window.apply(this, arguments).selectMany(function (x) { return x.toArray(); }); + }; + + /** + * Projects each element of an observable sequence into zero or more windows. + * + * @param {Mixed} windowOpeningsOrClosingSelector Observable sequence whose elements denote the creation of new windows, or, a function invoked to define the boundaries of the produced windows (a new window is started when the previous one is closed, resulting in non-overlapping windows). + * @param {Function} [windowClosingSelector] A function invoked to define the closing of each produced window. If a closing selector function is specified for the first parameter, this parameter is ignored. + * @returns {Observable} An observable sequence of windows. + */ + observableProto.window = function (windowOpeningsOrClosingSelector, windowClosingSelector) { + if (arguments.length === 1 && typeof arguments[0] !== 'function') { + return observableWindowWithBoundaries.call(this, windowOpeningsOrClosingSelector); + } + return typeof windowOpeningsOrClosingSelector === 'function' ? + observableWindowWithClosingSelector.call(this, windowOpeningsOrClosingSelector) : + observableWindowWithOpenings.call(this, windowOpeningsOrClosingSelector, windowClosingSelector); + }; + + function observableWindowWithOpenings(windowOpenings, windowClosingSelector) { + return windowOpenings.groupJoin(this, windowClosingSelector, observableEmpty, function (_, win) { + return win; + }); + } + + function observableWindowWithBoundaries(windowBoundaries) { + var source = this; + return new AnonymousObservable(function (observer) { + var win = new Subject(), + d = new CompositeDisposable(), + r = new RefCountDisposable(d); + + observer.onNext(addRef(win, r)); + + d.add(source.subscribe(function (x) { + win.onNext(x); + }, function (err) { + win.onError(err); + observer.onError(err); + }, function () { + win.onCompleted(); + observer.onCompleted(); + })); + + isPromise(windowBoundaries) && (windowBoundaries = observableFromPromise(windowBoundaries)); + + d.add(windowBoundaries.subscribe(function (w) { + win.onCompleted(); + win = new Subject(); + observer.onNext(addRef(win, r)); + }, function (err) { + win.onError(err); + observer.onError(err); + }, function () { + win.onCompleted(); + observer.onCompleted(); + })); + + return r; + }, source); + } + + function observableWindowWithClosingSelector(windowClosingSelector) { + var source = this; + return new AnonymousObservable(function (observer) { + var m = new SerialDisposable(), + d = new CompositeDisposable(m), + r = new RefCountDisposable(d), + win = new Subject(); + observer.onNext(addRef(win, r)); + d.add(source.subscribe(function (x) { + win.onNext(x); + }, function (err) { + win.onError(err); + observer.onError(err); + }, function () { + win.onCompleted(); + observer.onCompleted(); + })); + + function createWindowClose () { + var windowClose; + try { + windowClose = windowClosingSelector(); + } catch (e) { + observer.onError(e); + return; + } + + isPromise(windowClose) && (windowClose = observableFromPromise(windowClose)); + + var m1 = new SingleAssignmentDisposable(); + m.setDisposable(m1); + m1.setDisposable(windowClose.take(1).subscribe(noop, function (err) { + win.onError(err); + observer.onError(err); + }, function () { + win.onCompleted(); + win = new Subject(); + observer.onNext(addRef(win, r)); + createWindowClose(); + })); + } + + createWindowClose(); + return r; + }, source); + } + + /** + * Returns a new observable that triggers on the second and subsequent triggerings of the input observable. + * The Nth triggering of the input observable passes the arguments from the N-1th and Nth triggering as a pair. + * The argument passed to the N-1th triggering is held in hidden internal state until the Nth triggering occurs. + * @returns {Observable} An observable that triggers on successive pairs of observations from the input observable as an array. + */ + observableProto.pairwise = function () { + var source = this; + return new AnonymousObservable(function (observer) { + var previous, hasPrevious = false; + return source.subscribe( + function (x) { + if (hasPrevious) { + observer.onNext([previous, x]); + } else { + hasPrevious = true; + } + previous = x; + }, + observer.onError.bind(observer), + observer.onCompleted.bind(observer)); + }, source); + }; + + /** + * Returns two observables which partition the observations of the source by the given function. + * The first will trigger observations for those values for which the predicate returns true. + * The second will trigger observations for those values where the predicate returns false. + * The predicate is executed once for each subscribed observer. + * Both also propagate all error observations arising from the source and each completes + * when the source completes. + * @param {Function} predicate + * The function to determine which output Observable will trigger a particular observation. + * @returns {Array} + * An array of observables. The first triggers when the predicate returns true, + * and the second triggers when the predicate returns false. + */ + observableProto.partition = function(predicate, thisArg) { + return [ + this.filter(predicate, thisArg), + this.filter(function (x, i, o) { return !predicate.call(thisArg, x, i, o); }) + ]; + }; + + var WhileEnumerable = (function(__super__) { + inherits(WhileEnumerable, __super__); + function WhileEnumerable(c, s) { + this.c = c; + this.s = s; + } + WhileEnumerable.prototype[$iterator$] = function () { + var self = this; + return { + next: function () { + return self.c() ? + { done: false, value: self.s } : + { done: true, value: void 0 }; + } + }; + }; + return WhileEnumerable; + }(Enumerable)); + + function enumerableWhile(condition, source) { + return new WhileEnumerable(condition, source); + } + + /** + * Returns an observable sequence that is the result of invoking the selector on the source sequence, without sharing subscriptions. + * This operator allows for a fluent style of writing queries that use the same sequence multiple times. + * + * @param {Function} selector Selector function which can use the source sequence as many times as needed, without sharing subscriptions to the source sequence. + * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. + */ + observableProto.letBind = observableProto['let'] = function (func) { + return func(this); + }; + + /** + * Determines whether an observable collection contains values. There is an alias for this method called 'ifThen' for browsers 0) { + isOwner = !isAcquired; + isAcquired = true; + } + if (isOwner) { + m.setDisposable(scheduler.scheduleRecursive(function (self) { + var work; + if (q.length > 0) { + work = q.shift(); + } else { + isAcquired = false; + return; + } + var m1 = new SingleAssignmentDisposable(); + d.add(m1); + m1.setDisposable(work.subscribe(function (x) { + observer.onNext(x); + var result = null; + try { + result = selector(x); + } catch (e) { + observer.onError(e); + } + q.push(result); + activeCount++; + ensureActive(); + }, observer.onError.bind(observer), function () { + d.remove(m1); + activeCount--; + if (activeCount === 0) { + observer.onCompleted(); + } + })); + self(); + })); + } + }; + + q.push(source); + activeCount++; + ensureActive(); + return d; + }, this); + }; + + /** + * Runs all observable sequences in parallel and collect their last elements. + * + * @example + * 1 - res = Rx.Observable.forkJoin([obs1, obs2]); + * 1 - res = Rx.Observable.forkJoin(obs1, obs2, ...); + * @returns {Observable} An observable sequence with an array collecting the last elements of all the input sequences. + */ + Observable.forkJoin = function () { + var allSources = []; + if (Array.isArray(arguments[0])) { + allSources = arguments[0]; + } else { + for(var i = 0, len = arguments.length; i < len; i++) { allSources.push(arguments[i]); } + } + return new AnonymousObservable(function (subscriber) { + var count = allSources.length; + if (count === 0) { + subscriber.onCompleted(); + return disposableEmpty; + } + var group = new CompositeDisposable(), + finished = false, + hasResults = new Array(count), + hasCompleted = new Array(count), + results = new Array(count); + + for (var idx = 0; idx < count; idx++) { + (function (i) { + var source = allSources[i]; + isPromise(source) && (source = observableFromPromise(source)); + group.add( + source.subscribe( + function (value) { + if (!finished) { + hasResults[i] = true; + results[i] = value; + } + }, + function (e) { + finished = true; + subscriber.onError(e); + group.dispose(); + }, + function () { + if (!finished) { + if (!hasResults[i]) { + subscriber.onCompleted(); + return; + } + hasCompleted[i] = true; + for (var ix = 0; ix < count; ix++) { + if (!hasCompleted[ix]) { return; } + } + finished = true; + subscriber.onNext(results); + subscriber.onCompleted(); + } + })); + })(idx); + } + + return group; + }); + }; + + /** + * Runs two observable sequences in parallel and combines their last elemenets. + * + * @param {Observable} second Second observable sequence. + * @param {Function} resultSelector Result selector function to invoke with the last elements of both sequences. + * @returns {Observable} An observable sequence with the result of calling the selector function with the last elements of both input sequences. + */ + observableProto.forkJoin = function (second, resultSelector) { + var first = this; + return new AnonymousObservable(function (observer) { + var leftStopped = false, rightStopped = false, + hasLeft = false, hasRight = false, + lastLeft, lastRight, + leftSubscription = new SingleAssignmentDisposable(), rightSubscription = new SingleAssignmentDisposable(); + + isPromise(second) && (second = observableFromPromise(second)); + + leftSubscription.setDisposable( + first.subscribe(function (left) { + hasLeft = true; + lastLeft = left; + }, function (err) { + rightSubscription.dispose(); + observer.onError(err); + }, function () { + leftStopped = true; + if (rightStopped) { + if (!hasLeft) { + observer.onCompleted(); + } else if (!hasRight) { + observer.onCompleted(); + } else { + var result; + try { + result = resultSelector(lastLeft, lastRight); + } catch (e) { + observer.onError(e); + return; + } + observer.onNext(result); + observer.onCompleted(); + } + } + }) + ); + + rightSubscription.setDisposable( + second.subscribe(function (right) { + hasRight = true; + lastRight = right; + }, function (err) { + leftSubscription.dispose(); + observer.onError(err); + }, function () { + rightStopped = true; + if (leftStopped) { + if (!hasLeft) { + observer.onCompleted(); + } else if (!hasRight) { + observer.onCompleted(); + } else { + var result; + try { + result = resultSelector(lastLeft, lastRight); + } catch (e) { + observer.onError(e); + return; + } + observer.onNext(result); + observer.onCompleted(); + } + } + }) + ); + + return new CompositeDisposable(leftSubscription, rightSubscription); + }, first); + }; + + /** + * Comonadic bind operator. + * @param {Function} selector A transform function to apply to each element. + * @param {Object} scheduler Scheduler used to execute the operation. If not specified, defaults to the ImmediateScheduler. + * @returns {Observable} An observable sequence which results from the comonadic bind operation. + */ + observableProto.manySelect = observableProto.extend = function (selector, scheduler) { + isScheduler(scheduler) || (scheduler = immediateScheduler); + var source = this; + return observableDefer(function () { + var chain; + + return source + .map(function (x) { + var curr = new ChainObservable(x); + + chain && chain.onNext(x); + chain = curr; + + return curr; + }) + .tap( + noop, + function (e) { chain && chain.onError(e); }, + function () { chain && chain.onCompleted(); } + ) + .observeOn(scheduler) + .map(selector); + }, source); + }; + + var ChainObservable = (function (__super__) { + + function subscribe (observer) { + var self = this, g = new CompositeDisposable(); + g.add(currentThreadScheduler.schedule(function () { + observer.onNext(self.head); + g.add(self.tail.mergeAll().subscribe(observer)); + })); + + return g; + } + + inherits(ChainObservable, __super__); + + function ChainObservable(head) { + __super__.call(this, subscribe); + this.head = head; + this.tail = new AsyncSubject(); + } + + addProperties(ChainObservable.prototype, Observer, { + onCompleted: function () { + this.onNext(Observable.empty()); + }, + onError: function (e) { + this.onNext(Observable.throwError(e)); + }, + onNext: function (v) { + this.tail.onNext(v); + this.tail.onCompleted(); + } + }); + + return ChainObservable; + + }(Observable)); + + /** @private */ + var Map = root.Map || (function () { + + function Map() { + this._keys = []; + this._values = []; + } + + Map.prototype.get = function (key) { + var i = this._keys.indexOf(key); + return i !== -1 ? this._values[i] : undefined; + }; + + Map.prototype.set = function (key, value) { + var i = this._keys.indexOf(key); + i !== -1 && (this._values[i] = value); + this._values[this._keys.push(key) - 1] = value; + }; + + Map.prototype.forEach = function (callback, thisArg) { + for (var i = 0, len = this._keys.length; i < len; i++) { + callback.call(thisArg, this._values[i], this._keys[i]); + } + }; + + return Map; + }()); + + /** + * @constructor + * Represents a join pattern over observable sequences. + */ + function Pattern(patterns) { + this.patterns = patterns; + } + + /** + * Creates a pattern that matches the current plan matches and when the specified observable sequences has an available value. + * @param other Observable sequence to match in addition to the current pattern. + * @return {Pattern} Pattern object that matches when all observable sequences in the pattern have an available value. + */ + Pattern.prototype.and = function (other) { + return new Pattern(this.patterns.concat(other)); + }; + + /** + * Matches when all observable sequences in the pattern (specified using a chain of and operators) have an available value and projects the values. + * @param {Function} selector Selector that will be invoked with available values from the source sequences, in the same order of the sequences in the pattern. + * @return {Plan} Plan that produces the projected values, to be fed (with other plans) to the when operator. + */ + Pattern.prototype.thenDo = function (selector) { + return new Plan(this, selector); + }; + + function Plan(expression, selector) { + this.expression = expression; + this.selector = selector; + } + + Plan.prototype.activate = function (externalSubscriptions, observer, deactivate) { + var self = this; + var joinObservers = []; + for (var i = 0, len = this.expression.patterns.length; i < len; i++) { + joinObservers.push(planCreateObserver(externalSubscriptions, this.expression.patterns[i], observer.onError.bind(observer))); + } + var activePlan = new ActivePlan(joinObservers, function () { + var result; + try { + result = self.selector.apply(self, arguments); + } catch (e) { + observer.onError(e); + return; + } + observer.onNext(result); + }, function () { + for (var j = 0, jlen = joinObservers.length; j < jlen; j++) { + joinObservers[j].removeActivePlan(activePlan); + } + deactivate(activePlan); + }); + for (i = 0, len = joinObservers.length; i < len; i++) { + joinObservers[i].addActivePlan(activePlan); + } + return activePlan; + }; + + function planCreateObserver(externalSubscriptions, observable, onError) { + var entry = externalSubscriptions.get(observable); + if (!entry) { + var observer = new JoinObserver(observable, onError); + externalSubscriptions.set(observable, observer); + return observer; + } + return entry; + } + + function ActivePlan(joinObserverArray, onNext, onCompleted) { + this.joinObserverArray = joinObserverArray; + this.onNext = onNext; + this.onCompleted = onCompleted; + this.joinObservers = new Map(); + for (var i = 0, len = this.joinObserverArray.length; i < len; i++) { + var joinObserver = this.joinObserverArray[i]; + this.joinObservers.set(joinObserver, joinObserver); + } + } + + ActivePlan.prototype.dequeue = function () { + this.joinObservers.forEach(function (v) { v.queue.shift(); }); + }; + + ActivePlan.prototype.match = function () { + var i, len, hasValues = true; + for (i = 0, len = this.joinObserverArray.length; i < len; i++) { + if (this.joinObserverArray[i].queue.length === 0) { + hasValues = false; + break; + } + } + if (hasValues) { + var firstValues = [], + isCompleted = false; + for (i = 0, len = this.joinObserverArray.length; i < len; i++) { + firstValues.push(this.joinObserverArray[i].queue[0]); + this.joinObserverArray[i].queue[0].kind === 'C' && (isCompleted = true); + } + if (isCompleted) { + this.onCompleted(); + } else { + this.dequeue(); + var values = []; + for (i = 0, len = firstValues.length; i < firstValues.length; i++) { + values.push(firstValues[i].value); + } + this.onNext.apply(this, values); + } + } + }; + + var JoinObserver = (function (__super__) { + inherits(JoinObserver, __super__); + + function JoinObserver(source, onError) { + __super__.call(this); + this.source = source; + this.onError = onError; + this.queue = []; + this.activePlans = []; + this.subscription = new SingleAssignmentDisposable(); + this.isDisposed = false; + } + + var JoinObserverPrototype = JoinObserver.prototype; + + JoinObserverPrototype.next = function (notification) { + if (!this.isDisposed) { + if (notification.kind === 'E') { + return this.onError(notification.exception); + } + this.queue.push(notification); + var activePlans = this.activePlans.slice(0); + for (var i = 0, len = activePlans.length; i < len; i++) { + activePlans[i].match(); + } + } + }; + + JoinObserverPrototype.error = noop; + JoinObserverPrototype.completed = noop; + + JoinObserverPrototype.addActivePlan = function (activePlan) { + this.activePlans.push(activePlan); + }; + + JoinObserverPrototype.subscribe = function () { + this.subscription.setDisposable(this.source.materialize().subscribe(this)); + }; + + JoinObserverPrototype.removeActivePlan = function (activePlan) { + this.activePlans.splice(this.activePlans.indexOf(activePlan), 1); + this.activePlans.length === 0 && this.dispose(); + }; + + JoinObserverPrototype.dispose = function () { + __super__.prototype.dispose.call(this); + if (!this.isDisposed) { + this.isDisposed = true; + this.subscription.dispose(); + } + }; + + return JoinObserver; + } (AbstractObserver)); + + /** + * Creates a pattern that matches when both observable sequences have an available value. + * + * @param right Observable sequence to match with the current sequence. + * @return {Pattern} Pattern object that matches when both observable sequences have an available value. + */ + observableProto.and = function (right) { + return new Pattern([this, right]); + }; + + /** + * Matches when the observable sequence has an available value and projects the value. + * + * @param {Function} selector Selector that will be invoked for values in the source sequence. + * @returns {Plan} Plan that produces the projected values, to be fed (with other plans) to the when operator. + */ + observableProto.thenDo = function (selector) { + return new Pattern([this]).thenDo(selector); + }; + + /** + * Joins together the results from several patterns. + * + * @param plans A series of plans (specified as an Array of as a series of arguments) created by use of the Then operator on patterns. + * @returns {Observable} Observable sequence with the results form matching several patterns. + */ + Observable.when = function () { + var len = arguments.length, plans; + if (Array.isArray(arguments[0])) { + plans = arguments[0]; + } else { + plans = new Array(len); + for(var i = 0; i < len; i++) { plans[i] = arguments[i]; } + } + return new AnonymousObservable(function (o) { + var activePlans = [], + externalSubscriptions = new Map(); + var outObserver = observerCreate( + function (x) { o.onNext(x); }, + function (err) { + externalSubscriptions.forEach(function (v) { v.onError(err); }); + o.onError(err); + }, + function (x) { o.onCompleted(); } + ); + try { + for (var i = 0, len = plans.length; i < len; i++) { + activePlans.push(plans[i].activate(externalSubscriptions, outObserver, function (activePlan) { + var idx = activePlans.indexOf(activePlan); + activePlans.splice(idx, 1); + activePlans.length === 0 && o.onCompleted(); + })); + } + } catch (e) { + observableThrow(e).subscribe(o); + } + var group = new CompositeDisposable(); + externalSubscriptions.forEach(function (joinObserver) { + joinObserver.subscribe(); + group.add(joinObserver); + }); + + return group; + }); + }; + + function observableTimerDate(dueTime, scheduler) { + return new AnonymousObservable(function (observer) { + return scheduler.scheduleWithAbsolute(dueTime, function () { + observer.onNext(0); + observer.onCompleted(); + }); + }); + } + + function observableTimerDateAndPeriod(dueTime, period, scheduler) { + return new AnonymousObservable(function (observer) { + var d = dueTime, p = normalizeTime(period); + return scheduler.scheduleRecursiveWithAbsoluteAndState(0, d, function (count, self) { + if (p > 0) { + var now = scheduler.now(); + d = d + p; + d <= now && (d = now + p); + } + observer.onNext(count); + self(count + 1, d); + }); + }); + } + + function observableTimerTimeSpan(dueTime, scheduler) { + return new AnonymousObservable(function (observer) { + return scheduler.scheduleWithRelative(normalizeTime(dueTime), function () { + observer.onNext(0); + observer.onCompleted(); + }); + }); + } + + function observableTimerTimeSpanAndPeriod(dueTime, period, scheduler) { + return dueTime === period ? + new AnonymousObservable(function (observer) { + return scheduler.schedulePeriodicWithState(0, period, function (count) { + observer.onNext(count); + return count + 1; + }); + }) : + observableDefer(function () { + return observableTimerDateAndPeriod(scheduler.now() + dueTime, period, scheduler); + }); + } + + /** + * Returns an observable sequence that produces a value after each period. + * + * @example + * 1 - res = Rx.Observable.interval(1000); + * 2 - res = Rx.Observable.interval(1000, Rx.Scheduler.timeout); + * + * @param {Number} period Period for producing the values in the resulting sequence (specified as an integer denoting milliseconds). + * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, Rx.Scheduler.timeout is used. + * @returns {Observable} An observable sequence that produces a value after each period. + */ + var observableinterval = Observable.interval = function (period, scheduler) { + return observableTimerTimeSpanAndPeriod(period, period, isScheduler(scheduler) ? scheduler : timeoutScheduler); + }; + + /** + * Returns an observable sequence that produces a value after dueTime has elapsed and then after each period. + * @param {Number} dueTime Absolute (specified as a Date object) or relative time (specified as an integer denoting milliseconds) at which to produce the first value. + * @param {Mixed} [periodOrScheduler] Period to produce subsequent values (specified as an integer denoting milliseconds), or the scheduler to run the timer on. If not specified, the resulting timer is not recurring. + * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, the timeout scheduler is used. + * @returns {Observable} An observable sequence that produces a value after due time has elapsed and then each period. + */ + var observableTimer = Observable.timer = function (dueTime, periodOrScheduler, scheduler) { + var period; + isScheduler(scheduler) || (scheduler = timeoutScheduler); + if (periodOrScheduler !== undefined && typeof periodOrScheduler === 'number') { + period = periodOrScheduler; + } else if (isScheduler(periodOrScheduler)) { + scheduler = periodOrScheduler; + } + if (dueTime instanceof Date && period === undefined) { + return observableTimerDate(dueTime.getTime(), scheduler); + } + if (dueTime instanceof Date && period !== undefined) { + period = periodOrScheduler; + return observableTimerDateAndPeriod(dueTime.getTime(), period, scheduler); + } + return period === undefined ? + observableTimerTimeSpan(dueTime, scheduler) : + observableTimerTimeSpanAndPeriod(dueTime, period, scheduler); + }; + + function observableDelayTimeSpan(source, dueTime, scheduler) { + return new AnonymousObservable(function (observer) { + var active = false, + cancelable = new SerialDisposable(), + exception = null, + q = [], + running = false, + subscription; + subscription = source.materialize().timestamp(scheduler).subscribe(function (notification) { + var d, shouldRun; + if (notification.value.kind === 'E') { + q = []; + q.push(notification); + exception = notification.value.exception; + shouldRun = !running; + } else { + q.push({ value: notification.value, timestamp: notification.timestamp + dueTime }); + shouldRun = !active; + active = true; + } + if (shouldRun) { + if (exception !== null) { + observer.onError(exception); + } else { + d = new SingleAssignmentDisposable(); + cancelable.setDisposable(d); + d.setDisposable(scheduler.scheduleRecursiveWithRelative(dueTime, function (self) { + var e, recurseDueTime, result, shouldRecurse; + if (exception !== null) { + return; + } + running = true; + do { + result = null; + if (q.length > 0 && q[0].timestamp - scheduler.now() <= 0) { + result = q.shift().value; + } + if (result !== null) { + result.accept(observer); + } + } while (result !== null); + shouldRecurse = false; + recurseDueTime = 0; + if (q.length > 0) { + shouldRecurse = true; + recurseDueTime = Math.max(0, q[0].timestamp - scheduler.now()); + } else { + active = false; + } + e = exception; + running = false; + if (e !== null) { + observer.onError(e); + } else if (shouldRecurse) { + self(recurseDueTime); + } + })); + } + } + }); + return new CompositeDisposable(subscription, cancelable); + }, source); + } + + function observableDelayDate(source, dueTime, scheduler) { + return observableDefer(function () { + return observableDelayTimeSpan(source, dueTime - scheduler.now(), scheduler); + }); + } + + /** + * Time shifts the observable sequence by dueTime. The relative time intervals between the values are preserved. + * + * @example + * 1 - res = Rx.Observable.delay(new Date()); + * 2 - res = Rx.Observable.delay(new Date(), Rx.Scheduler.timeout); + * + * 3 - res = Rx.Observable.delay(5000); + * 4 - res = Rx.Observable.delay(5000, 1000, Rx.Scheduler.timeout); + * @memberOf Observable# + * @param {Number} dueTime Absolute (specified as a Date object) or relative time (specified as an integer denoting milliseconds) by which to shift the observable sequence. + * @param {Scheduler} [scheduler] Scheduler to run the delay timers on. If not specified, the timeout scheduler is used. + * @returns {Observable} Time-shifted sequence. + */ + observableProto.delay = function (dueTime, scheduler) { + isScheduler(scheduler) || (scheduler = timeoutScheduler); + return dueTime instanceof Date ? + observableDelayDate(this, dueTime.getTime(), scheduler) : + observableDelayTimeSpan(this, dueTime, scheduler); + }; + + /** + * Ignores values from an observable sequence which are followed by another value before dueTime. + * @param {Number} dueTime Duration of the debounce period for each value (specified as an integer denoting milliseconds). + * @param {Scheduler} [scheduler] Scheduler to run the debounce timers on. If not specified, the timeout scheduler is used. + * @returns {Observable} The debounced sequence. + */ + observableProto.debounce = observableProto.throttleWithTimeout = function (dueTime, scheduler) { + isScheduler(scheduler) || (scheduler = timeoutScheduler); + var source = this; + return new AnonymousObservable(function (observer) { + var cancelable = new SerialDisposable(), hasvalue = false, value, id = 0; + var subscription = source.subscribe( + function (x) { + hasvalue = true; + value = x; + id++; + var currentId = id, + d = new SingleAssignmentDisposable(); + cancelable.setDisposable(d); + d.setDisposable(scheduler.scheduleWithRelative(dueTime, function () { + hasvalue && id === currentId && observer.onNext(value); + hasvalue = false; + })); + }, + function (e) { + cancelable.dispose(); + observer.onError(e); + hasvalue = false; + id++; + }, + function () { + cancelable.dispose(); + hasvalue && observer.onNext(value); + observer.onCompleted(); + hasvalue = false; + id++; + }); + return new CompositeDisposable(subscription, cancelable); + }, this); + }; + + /** + * @deprecated use #debounce or #throttleWithTimeout instead. + */ + observableProto.throttle = function(dueTime, scheduler) { + //deprecate('throttle', 'debounce or throttleWithTimeout'); + return this.debounce(dueTime, scheduler); + }; + + /** + * Projects each element of an observable sequence into zero or more windows which are produced based on timing information. + * @param {Number} timeSpan Length of each window (specified as an integer denoting milliseconds). + * @param {Mixed} [timeShiftOrScheduler] Interval between creation of consecutive windows (specified as an integer denoting milliseconds), or an optional scheduler parameter. If not specified, the time shift corresponds to the timeSpan parameter, resulting in non-overlapping adjacent windows. + * @param {Scheduler} [scheduler] Scheduler to run windowing timers on. If not specified, the timeout scheduler is used. + * @returns {Observable} An observable sequence of windows. + */ + observableProto.windowWithTime = function (timeSpan, timeShiftOrScheduler, scheduler) { + var source = this, timeShift; + timeShiftOrScheduler == null && (timeShift = timeSpan); + isScheduler(scheduler) || (scheduler = timeoutScheduler); + if (typeof timeShiftOrScheduler === 'number') { + timeShift = timeShiftOrScheduler; + } else if (isScheduler(timeShiftOrScheduler)) { + timeShift = timeSpan; + scheduler = timeShiftOrScheduler; + } + return new AnonymousObservable(function (observer) { + var groupDisposable, + nextShift = timeShift, + nextSpan = timeSpan, + q = [], + refCountDisposable, + timerD = new SerialDisposable(), + totalTime = 0; + groupDisposable = new CompositeDisposable(timerD), + refCountDisposable = new RefCountDisposable(groupDisposable); + + function createTimer () { + var m = new SingleAssignmentDisposable(), + isSpan = false, + isShift = false; + timerD.setDisposable(m); + if (nextSpan === nextShift) { + isSpan = true; + isShift = true; + } else if (nextSpan < nextShift) { + isSpan = true; + } else { + isShift = true; + } + var newTotalTime = isSpan ? nextSpan : nextShift, + ts = newTotalTime - totalTime; + totalTime = newTotalTime; + if (isSpan) { + nextSpan += timeShift; + } + if (isShift) { + nextShift += timeShift; + } + m.setDisposable(scheduler.scheduleWithRelative(ts, function () { + if (isShift) { + var s = new Subject(); + q.push(s); + observer.onNext(addRef(s, refCountDisposable)); + } + isSpan && q.shift().onCompleted(); + createTimer(); + })); + }; + q.push(new Subject()); + observer.onNext(addRef(q[0], refCountDisposable)); + createTimer(); + groupDisposable.add(source.subscribe( + function (x) { + for (var i = 0, len = q.length; i < len; i++) { q[i].onNext(x); } + }, + function (e) { + for (var i = 0, len = q.length; i < len; i++) { q[i].onError(e); } + observer.onError(e); + }, + function () { + for (var i = 0, len = q.length; i < len; i++) { q[i].onCompleted(); } + observer.onCompleted(); + } + )); + return refCountDisposable; + }, source); + }; + + /** + * Projects each element of an observable sequence into a window that is completed when either it's full or a given amount of time has elapsed. + * @param {Number} timeSpan Maximum time length of a window. + * @param {Number} count Maximum element count of a window. + * @param {Scheduler} [scheduler] Scheduler to run windowing timers on. If not specified, the timeout scheduler is used. + * @returns {Observable} An observable sequence of windows. + */ + observableProto.windowWithTimeOrCount = function (timeSpan, count, scheduler) { + var source = this; + isScheduler(scheduler) || (scheduler = timeoutScheduler); + return new AnonymousObservable(function (observer) { + var timerD = new SerialDisposable(), + groupDisposable = new CompositeDisposable(timerD), + refCountDisposable = new RefCountDisposable(groupDisposable), + n = 0, + windowId = 0, + s = new Subject(); + + function createTimer(id) { + var m = new SingleAssignmentDisposable(); + timerD.setDisposable(m); + m.setDisposable(scheduler.scheduleWithRelative(timeSpan, function () { + if (id !== windowId) { return; } + n = 0; + var newId = ++windowId; + s.onCompleted(); + s = new Subject(); + observer.onNext(addRef(s, refCountDisposable)); + createTimer(newId); + })); + } + + observer.onNext(addRef(s, refCountDisposable)); + createTimer(0); + + groupDisposable.add(source.subscribe( + function (x) { + var newId = 0, newWindow = false; + s.onNext(x); + if (++n === count) { + newWindow = true; + n = 0; + newId = ++windowId; + s.onCompleted(); + s = new Subject(); + observer.onNext(addRef(s, refCountDisposable)); + } + newWindow && createTimer(newId); + }, + function (e) { + s.onError(e); + observer.onError(e); + }, function () { + s.onCompleted(); + observer.onCompleted(); + } + )); + return refCountDisposable; + }, source); + }; + + /** + * Projects each element of an observable sequence into zero or more buffers which are produced based on timing information. + * + * @example + * 1 - res = xs.bufferWithTime(1000, scheduler); // non-overlapping segments of 1 second + * 2 - res = xs.bufferWithTime(1000, 500, scheduler; // segments of 1 second with time shift 0.5 seconds + * + * @param {Number} timeSpan Length of each buffer (specified as an integer denoting milliseconds). + * @param {Mixed} [timeShiftOrScheduler] Interval between creation of consecutive buffers (specified as an integer denoting milliseconds), or an optional scheduler parameter. If not specified, the time shift corresponds to the timeSpan parameter, resulting in non-overlapping adjacent buffers. + * @param {Scheduler} [scheduler] Scheduler to run buffer timers on. If not specified, the timeout scheduler is used. + * @returns {Observable} An observable sequence of buffers. + */ + observableProto.bufferWithTime = function (timeSpan, timeShiftOrScheduler, scheduler) { + return this.windowWithTime.apply(this, arguments).selectMany(function (x) { return x.toArray(); }); + }; + + /** + * Projects each element of an observable sequence into a buffer that is completed when either it's full or a given amount of time has elapsed. + * + * @example + * 1 - res = source.bufferWithTimeOrCount(5000, 50); // 5s or 50 items in an array + * 2 - res = source.bufferWithTimeOrCount(5000, 50, scheduler); // 5s or 50 items in an array + * + * @param {Number} timeSpan Maximum time length of a buffer. + * @param {Number} count Maximum element count of a buffer. + * @param {Scheduler} [scheduler] Scheduler to run bufferin timers on. If not specified, the timeout scheduler is used. + * @returns {Observable} An observable sequence of buffers. + */ + observableProto.bufferWithTimeOrCount = function (timeSpan, count, scheduler) { + return this.windowWithTimeOrCount(timeSpan, count, scheduler).selectMany(function (x) { + return x.toArray(); + }); + }; + + /** + * Records the time interval between consecutive values in an observable sequence. + * + * @example + * 1 - res = source.timeInterval(); + * 2 - res = source.timeInterval(Rx.Scheduler.timeout); + * + * @param [scheduler] Scheduler used to compute time intervals. If not specified, the timeout scheduler is used. + * @returns {Observable} An observable sequence with time interval information on values. + */ + observableProto.timeInterval = function (scheduler) { + var source = this; + isScheduler(scheduler) || (scheduler = timeoutScheduler); + return observableDefer(function () { + var last = scheduler.now(); + return source.map(function (x) { + var now = scheduler.now(), span = now - last; + last = now; + return { value: x, interval: span }; + }); + }); + }; + + /** + * Records the timestamp for each value in an observable sequence. + * + * @example + * 1 - res = source.timestamp(); // produces { value: x, timestamp: ts } + * 2 - res = source.timestamp(Rx.Scheduler.default); + * + * @param {Scheduler} [scheduler] Scheduler used to compute timestamps. If not specified, the default scheduler is used. + * @returns {Observable} An observable sequence with timestamp information on values. + */ + observableProto.timestamp = function (scheduler) { + isScheduler(scheduler) || (scheduler = timeoutScheduler); + return this.map(function (x) { + return { value: x, timestamp: scheduler.now() }; + }); + }; + + function sampleObservable(source, sampler) { + return new AnonymousObservable(function (o) { + var atEnd = false, value, hasValue = false; + + function sampleSubscribe() { + if (hasValue) { + hasValue = false; + o.onNext(value); + } + atEnd && o.onCompleted(); + } + + var sourceSubscription = new SingleAssignmentDisposable(); + sourceSubscription.setDisposable(source.subscribe( + function (newValue) { + hasValue = true; + value = newValue; + }, + function (e) { o.onError(e); }, + function () { + atEnd = true; + sourceSubscription.dispose(); + } + )); + + return new CompositeDisposable( + sourceSubscription, + sampler.subscribe(sampleSubscribe, function (e) { o.onError(e); }, sampleSubscribe) + ); + }, source); + } + + /** + * Samples the observable sequence at each interval. + * + * @example + * 1 - res = source.sample(sampleObservable); // Sampler tick sequence + * 2 - res = source.sample(5000); // 5 seconds + * 2 - res = source.sample(5000, Rx.Scheduler.timeout); // 5 seconds + * + * @param {Mixed} intervalOrSampler Interval at which to sample (specified as an integer denoting milliseconds) or Sampler Observable. + * @param {Scheduler} [scheduler] Scheduler to run the sampling timer on. If not specified, the timeout scheduler is used. + * @returns {Observable} Sampled observable sequence. + */ + observableProto.sample = observableProto.throttleLatest = function (intervalOrSampler, scheduler) { + isScheduler(scheduler) || (scheduler = timeoutScheduler); + return typeof intervalOrSampler === 'number' ? + sampleObservable(this, observableinterval(intervalOrSampler, scheduler)) : + sampleObservable(this, intervalOrSampler); + }; + + /** + * Returns the source observable sequence or the other observable sequence if dueTime elapses. + * @param {Number} dueTime Absolute (specified as a Date object) or relative time (specified as an integer denoting milliseconds) when a timeout occurs. + * @param {Observable} [other] Sequence to return in case of a timeout. If not specified, a timeout error throwing sequence will be used. + * @param {Scheduler} [scheduler] Scheduler to run the timeout timers on. If not specified, the timeout scheduler is used. + * @returns {Observable} The source sequence switching to the other sequence in case of a timeout. + */ + observableProto.timeout = function (dueTime, other, scheduler) { + (other == null || typeof other === 'string') && (other = observableThrow(new Error(other || 'Timeout'))); + isScheduler(scheduler) || (scheduler = timeoutScheduler); + + var source = this, schedulerMethod = dueTime instanceof Date ? + 'scheduleWithAbsolute' : + 'scheduleWithRelative'; + + return new AnonymousObservable(function (observer) { + var id = 0, + original = new SingleAssignmentDisposable(), + subscription = new SerialDisposable(), + switched = false, + timer = new SerialDisposable(); + + subscription.setDisposable(original); + + function createTimer() { + var myId = id; + timer.setDisposable(scheduler[schedulerMethod](dueTime, function () { + if (id === myId) { + isPromise(other) && (other = observableFromPromise(other)); + subscription.setDisposable(other.subscribe(observer)); + } + })); + } + + createTimer(); + + original.setDisposable(source.subscribe(function (x) { + if (!switched) { + id++; + observer.onNext(x); + createTimer(); + } + }, function (e) { + if (!switched) { + id++; + observer.onError(e); + } + }, function () { + if (!switched) { + id++; + observer.onCompleted(); + } + })); + return new CompositeDisposable(subscription, timer); + }, source); + }; + + /** + * Generates an observable sequence by iterating a state from an initial state until the condition fails. + * + * @example + * res = source.generateWithAbsoluteTime(0, + * function (x) { return return true; }, + * function (x) { return x + 1; }, + * function (x) { return x; }, + * function (x) { return new Date(); } + * }); + * + * @param {Mixed} initialState Initial state. + * @param {Function} condition Condition to terminate generation (upon returning false). + * @param {Function} iterate Iteration step function. + * @param {Function} resultSelector Selector function for results produced in the sequence. + * @param {Function} timeSelector Time selector function to control the speed of values being produced each iteration, returning Date values. + * @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not specified, the timeout scheduler is used. + * @returns {Observable} The generated sequence. + */ + Observable.generateWithAbsoluteTime = function (initialState, condition, iterate, resultSelector, timeSelector, scheduler) { + isScheduler(scheduler) || (scheduler = timeoutScheduler); + return new AnonymousObservable(function (observer) { + var first = true, + hasResult = false; + return scheduler.scheduleRecursiveWithAbsoluteAndState(initialState, scheduler.now(), function (state, self) { + hasResult && observer.onNext(state); + + try { + if (first) { + first = false; + } else { + state = iterate(state); + } + hasResult = condition(state); + if (hasResult) { + var result = resultSelector(state); + var time = timeSelector(state); + } + } catch (e) { + observer.onError(e); + return; + } + if (hasResult) { + self(result, time); + } else { + observer.onCompleted(); + } + }); + }); + }; + + /** + * Generates an observable sequence by iterating a state from an initial state until the condition fails. + * + * @example + * res = source.generateWithRelativeTime(0, + * function (x) { return return true; }, + * function (x) { return x + 1; }, + * function (x) { return x; }, + * function (x) { return 500; } + * ); + * + * @param {Mixed} initialState Initial state. + * @param {Function} condition Condition to terminate generation (upon returning false). + * @param {Function} iterate Iteration step function. + * @param {Function} resultSelector Selector function for results produced in the sequence. + * @param {Function} timeSelector Time selector function to control the speed of values being produced each iteration, returning integer values denoting milliseconds. + * @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not specified, the timeout scheduler is used. + * @returns {Observable} The generated sequence. + */ + Observable.generateWithRelativeTime = function (initialState, condition, iterate, resultSelector, timeSelector, scheduler) { + isScheduler(scheduler) || (scheduler = timeoutScheduler); + return new AnonymousObservable(function (observer) { + var first = true, + hasResult = false; + return scheduler.scheduleRecursiveWithRelativeAndState(initialState, 0, function (state, self) { + hasResult && observer.onNext(state); + + try { + if (first) { + first = false; + } else { + state = iterate(state); + } + hasResult = condition(state); + if (hasResult) { + var result = resultSelector(state); + var time = timeSelector(state); + } + } catch (e) { + observer.onError(e); + return; + } + if (hasResult) { + self(result, time); + } else { + observer.onCompleted(); + } + }); + }); + }; + + /** + * Time shifts the observable sequence by delaying the subscription with the specified relative time duration, using the specified scheduler to run timers. + * + * @example + * 1 - res = source.delaySubscription(5000); // 5s + * 2 - res = source.delaySubscription(5000, Rx.Scheduler.default); // 5 seconds + * + * @param {Number} dueTime Relative or absolute time shift of the subscription. + * @param {Scheduler} [scheduler] Scheduler to run the subscription delay timer on. If not specified, the timeout scheduler is used. + * @returns {Observable} Time-shifted sequence. + */ + observableProto.delaySubscription = function (dueTime, scheduler) { + var scheduleMethod = dueTime instanceof Date ? 'scheduleWithAbsolute' : 'scheduleWithRelative'; + var source = this; + isScheduler(scheduler) || (scheduler = timeoutScheduler); + return new AnonymousObservable(function (o) { + var d = new SerialDisposable(); + + d.setDisposable(scheduler[scheduleMethod](dueTime, function() { + d.setDisposable(source.subscribe(o)); + })); + + return d; + }, this); + }; + + /** + * Time shifts the observable sequence based on a subscription delay and a delay selector function for each element. + * + * @example + * 1 - res = source.delayWithSelector(function (x) { return Rx.Scheduler.timer(5000); }); // with selector only + * 1 - res = source.delayWithSelector(Rx.Observable.timer(2000), function (x) { return Rx.Observable.timer(x); }); // with delay and selector + * + * @param {Observable} [subscriptionDelay] Sequence indicating the delay for the subscription to the source. + * @param {Function} delayDurationSelector Selector function to retrieve a sequence indicating the delay for each given element. + * @returns {Observable} Time-shifted sequence. + */ + observableProto.delayWithSelector = function (subscriptionDelay, delayDurationSelector) { + var source = this, subDelay, selector; + if (isFunction(subscriptionDelay)) { + selector = subscriptionDelay; + } else { + subDelay = subscriptionDelay; + selector = delayDurationSelector; + } + return new AnonymousObservable(function (observer) { + var delays = new CompositeDisposable(), atEnd = false, subscription = new SerialDisposable(); + + function start() { + subscription.setDisposable(source.subscribe( + function (x) { + var delay = tryCatch(selector)(x); + if (delay === errorObj) { return observer.onError(delay.e); } + var d = new SingleAssignmentDisposable(); + delays.add(d); + d.setDisposable(delay.subscribe( + function () { + observer.onNext(x); + delays.remove(d); + done(); + }, + function (e) { observer.onError(e); }, + function () { + observer.onNext(x); + delays.remove(d); + done(); + } + )) + }, + function (e) { observer.onError(e); }, + function () { + atEnd = true; + subscription.dispose(); + done(); + } + )) + } + + function done () { + atEnd && delays.length === 0 && observer.onCompleted(); + } + + if (!subDelay) { + start(); + } else { + subscription.setDisposable(subDelay.subscribe(start, function (e) { observer.onError(e); }, start)); + } + + return new CompositeDisposable(subscription, delays); + }, this); + }; + + /** + * Returns the source observable sequence, switching to the other observable sequence if a timeout is signaled. + * @param {Observable} [firstTimeout] Observable sequence that represents the timeout for the first element. If not provided, this defaults to Observable.never(). + * @param {Function} timeoutDurationSelector Selector to retrieve an observable sequence that represents the timeout between the current element and the next element. + * @param {Observable} [other] Sequence to return in case of a timeout. If not provided, this is set to Observable.throwException(). + * @returns {Observable} The source sequence switching to the other sequence in case of a timeout. + */ + observableProto.timeoutWithSelector = function (firstTimeout, timeoutdurationSelector, other) { + if (arguments.length === 1) { + timeoutdurationSelector = firstTimeout; + firstTimeout = observableNever(); + } + other || (other = observableThrow(new Error('Timeout'))); + var source = this; + return new AnonymousObservable(function (observer) { + var subscription = new SerialDisposable(), timer = new SerialDisposable(), original = new SingleAssignmentDisposable(); + + subscription.setDisposable(original); + + var id = 0, switched = false; + + function setTimer(timeout) { + var myId = id; + + function timerWins () { + return id === myId; + } + + var d = new SingleAssignmentDisposable(); + timer.setDisposable(d); + d.setDisposable(timeout.subscribe(function () { + timerWins() && subscription.setDisposable(other.subscribe(observer)); + d.dispose(); + }, function (e) { + timerWins() && observer.onError(e); + }, function () { + timerWins() && subscription.setDisposable(other.subscribe(observer)); + })); + }; + + setTimer(firstTimeout); + + function observerWins() { + var res = !switched; + if (res) { id++; } + return res; + } + + original.setDisposable(source.subscribe(function (x) { + if (observerWins()) { + observer.onNext(x); + var timeout; + try { + timeout = timeoutdurationSelector(x); + } catch (e) { + observer.onError(e); + return; + } + setTimer(isPromise(timeout) ? observableFromPromise(timeout) : timeout); + } + }, function (e) { + observerWins() && observer.onError(e); + }, function () { + observerWins() && observer.onCompleted(); + })); + return new CompositeDisposable(subscription, timer); + }, source); + }; + + /** + * Ignores values from an observable sequence which are followed by another value within a computed throttle duration. + * @param {Function} durationSelector Selector function to retrieve a sequence indicating the throttle duration for each given element. + * @returns {Observable} The debounced sequence. + */ + observableProto.debounceWithSelector = function (durationSelector) { + var source = this; + return new AnonymousObservable(function (observer) { + var value, hasValue = false, cancelable = new SerialDisposable(), id = 0; + var subscription = source.subscribe(function (x) { + var throttle; + try { + throttle = durationSelector(x); + } catch (e) { + observer.onError(e); + return; + } + + isPromise(throttle) && (throttle = observableFromPromise(throttle)); + + hasValue = true; + value = x; + id++; + var currentid = id, d = new SingleAssignmentDisposable(); + cancelable.setDisposable(d); + d.setDisposable(throttle.subscribe(function () { + hasValue && id === currentid && observer.onNext(value); + hasValue = false; + d.dispose(); + }, observer.onError.bind(observer), function () { + hasValue && id === currentid && observer.onNext(value); + hasValue = false; + d.dispose(); + })); + }, function (e) { + cancelable.dispose(); + observer.onError(e); + hasValue = false; + id++; + }, function () { + cancelable.dispose(); + hasValue && observer.onNext(value); + observer.onCompleted(); + hasValue = false; + id++; + }); + return new CompositeDisposable(subscription, cancelable); + }, source); + }; + + /** + * @deprecated use #debounceWithSelector instead. + */ + observableProto.throttleWithSelector = function (durationSelector) { + //deprecate('throttleWithSelector', 'debounceWithSelector'); + return this.debounceWithSelector(durationSelector); + }; + + /** + * Skips elements for the specified duration from the end of the observable source sequence, using the specified scheduler to run timers. + * + * 1 - res = source.skipLastWithTime(5000); + * 2 - res = source.skipLastWithTime(5000, scheduler); + * + * @description + * This operator accumulates a queue with a length enough to store elements received during the initial duration window. + * As more elements are received, elements older than the specified duration are taken from the queue and produced on the + * result sequence. This causes elements to be delayed with duration. + * @param {Number} duration Duration for skipping elements from the end of the sequence. + * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout + * @returns {Observable} An observable sequence with the elements skipped during the specified duration from the end of the source sequence. + */ + observableProto.skipLastWithTime = function (duration, scheduler) { + isScheduler(scheduler) || (scheduler = timeoutScheduler); + var source = this; + return new AnonymousObservable(function (o) { + var q = []; + return source.subscribe(function (x) { + var now = scheduler.now(); + q.push({ interval: now, value: x }); + while (q.length > 0 && now - q[0].interval >= duration) { + o.onNext(q.shift().value); + } + }, function (e) { o.onError(e); }, function () { + var now = scheduler.now(); + while (q.length > 0 && now - q[0].interval >= duration) { + o.onNext(q.shift().value); + } + o.onCompleted(); + }); + }, source); + }; + + /** + * Returns elements within the specified duration from the end of the observable source sequence, using the specified schedulers to run timers and to drain the collected elements. + * @description + * This operator accumulates a queue with a length enough to store elements received during the initial duration window. + * As more elements are received, elements older than the specified duration are taken from the queue and produced on the + * result sequence. This causes elements to be delayed with duration. + * @param {Number} duration Duration for taking elements from the end of the sequence. + * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. + * @returns {Observable} An observable sequence with the elements taken during the specified duration from the end of the source sequence. + */ + observableProto.takeLastWithTime = function (duration, scheduler) { + var source = this; + isScheduler(scheduler) || (scheduler = timeoutScheduler); + return new AnonymousObservable(function (o) { + var q = []; + return source.subscribe(function (x) { + var now = scheduler.now(); + q.push({ interval: now, value: x }); + while (q.length > 0 && now - q[0].interval >= duration) { + q.shift(); + } + }, function (e) { o.onError(e); }, function () { + var now = scheduler.now(); + while (q.length > 0) { + var next = q.shift(); + if (now - next.interval <= duration) { o.onNext(next.value); } + } + o.onCompleted(); + }); + }, source); + }; + + /** + * Returns an array with the elements within the specified duration from the end of the observable source sequence, using the specified scheduler to run timers. + * @description + * This operator accumulates a queue with a length enough to store elements received during the initial duration window. + * As more elements are received, elements older than the specified duration are taken from the queue and produced on the + * result sequence. This causes elements to be delayed with duration. + * @param {Number} duration Duration for taking elements from the end of the sequence. + * @param {Scheduler} scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. + * @returns {Observable} An observable sequence containing a single array with the elements taken during the specified duration from the end of the source sequence. + */ + observableProto.takeLastBufferWithTime = function (duration, scheduler) { + var source = this; + isScheduler(scheduler) || (scheduler = timeoutScheduler); + return new AnonymousObservable(function (o) { + var q = []; + return source.subscribe(function (x) { + var now = scheduler.now(); + q.push({ interval: now, value: x }); + while (q.length > 0 && now - q[0].interval >= duration) { + q.shift(); + } + }, function (e) { o.onError(e); }, function () { + var now = scheduler.now(), res = []; + while (q.length > 0) { + var next = q.shift(); + now - next.interval <= duration && res.push(next.value); + } + o.onNext(res); + o.onCompleted(); + }); + }, source); + }; + + /** + * Takes elements for the specified duration from the start of the observable source sequence, using the specified scheduler to run timers. + * + * @example + * 1 - res = source.takeWithTime(5000, [optional scheduler]); + * @description + * This operator accumulates a queue with a length enough to store elements received during the initial duration window. + * As more elements are received, elements older than the specified duration are taken from the queue and produced on the + * result sequence. This causes elements to be delayed with duration. + * @param {Number} duration Duration for taking elements from the start of the sequence. + * @param {Scheduler} scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. + * @returns {Observable} An observable sequence with the elements taken during the specified duration from the start of the source sequence. + */ + observableProto.takeWithTime = function (duration, scheduler) { + var source = this; + isScheduler(scheduler) || (scheduler = timeoutScheduler); + return new AnonymousObservable(function (o) { + return new CompositeDisposable(scheduler.scheduleWithRelative(duration, function () { o.onCompleted(); }), source.subscribe(o)); + }, source); + }; + + /** + * Skips elements for the specified duration from the start of the observable source sequence, using the specified scheduler to run timers. + * + * @example + * 1 - res = source.skipWithTime(5000, [optional scheduler]); + * + * @description + * Specifying a zero value for duration doesn't guarantee no elements will be dropped from the start of the source sequence. + * This is a side-effect of the asynchrony introduced by the scheduler, where the action that causes callbacks from the source sequence to be forwarded + * may not execute immediately, despite the zero due time. + * + * Errors produced by the source sequence are always forwarded to the result sequence, even if the error occurs before the duration. + * @param {Number} duration Duration for skipping elements from the start of the sequence. + * @param {Scheduler} scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. + * @returns {Observable} An observable sequence with the elements skipped during the specified duration from the start of the source sequence. + */ + observableProto.skipWithTime = function (duration, scheduler) { + var source = this; + isScheduler(scheduler) || (scheduler = timeoutScheduler); + return new AnonymousObservable(function (observer) { + var open = false; + return new CompositeDisposable( + scheduler.scheduleWithRelative(duration, function () { open = true; }), + source.subscribe(function (x) { open && observer.onNext(x); }, observer.onError.bind(observer), observer.onCompleted.bind(observer))); + }, source); + }; + + /** + * Skips elements from the observable source sequence until the specified start time, using the specified scheduler to run timers. + * Errors produced by the source sequence are always forwarded to the result sequence, even if the error occurs before the start time. + * + * @examples + * 1 - res = source.skipUntilWithTime(new Date(), [scheduler]); + * 2 - res = source.skipUntilWithTime(5000, [scheduler]); + * @param {Date|Number} startTime Time to start taking elements from the source sequence. If this value is less than or equal to Date(), no elements will be skipped. + * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. + * @returns {Observable} An observable sequence with the elements skipped until the specified start time. + */ + observableProto.skipUntilWithTime = function (startTime, scheduler) { + isScheduler(scheduler) || (scheduler = timeoutScheduler); + var source = this, schedulerMethod = startTime instanceof Date ? + 'scheduleWithAbsolute' : + 'scheduleWithRelative'; + return new AnonymousObservable(function (o) { + var open = false; + + return new CompositeDisposable( + scheduler[schedulerMethod](startTime, function () { open = true; }), + source.subscribe( + function (x) { open && o.onNext(x); }, + function (e) { o.onError(e); }, function () { o.onCompleted(); })); + }, source); + }; + + /** + * Takes elements for the specified duration until the specified end time, using the specified scheduler to run timers. + * @param {Number | Date} endTime Time to stop taking elements from the source sequence. If this value is less than or equal to new Date(), the result stream will complete immediately. + * @param {Scheduler} [scheduler] Scheduler to run the timer on. + * @returns {Observable} An observable sequence with the elements taken until the specified end time. + */ + observableProto.takeUntilWithTime = function (endTime, scheduler) { + isScheduler(scheduler) || (scheduler = timeoutScheduler); + var source = this, schedulerMethod = endTime instanceof Date ? + 'scheduleWithAbsolute' : + 'scheduleWithRelative'; + return new AnonymousObservable(function (o) { + return new CompositeDisposable( + scheduler[schedulerMethod](endTime, function () { o.onCompleted(); }), + source.subscribe(o)); + }, source); + }; + + /** + * Returns an Observable that emits only the first item emitted by the source Observable during sequential time windows of a specified duration. + * @param {Number} windowDuration time to wait before emitting another item after emitting the last item + * @param {Scheduler} [scheduler] the Scheduler to use internally to manage the timers that handle timeout for each item. If not provided, defaults to Scheduler.timeout. + * @returns {Observable} An Observable that performs the throttle operation. + */ + observableProto.throttleFirst = function (windowDuration, scheduler) { + isScheduler(scheduler) || (scheduler = timeoutScheduler); + var duration = +windowDuration || 0; + if (duration <= 0) { throw new RangeError('windowDuration cannot be less or equal zero.'); } + var source = this; + return new AnonymousObservable(function (o) { + var lastOnNext = 0; + return source.subscribe( + function (x) { + var now = scheduler.now(); + if (lastOnNext === 0 || now - lastOnNext >= duration) { + lastOnNext = now; + o.onNext(x); + } + },function (e) { o.onError(e); }, function () { o.onCompleted(); } + ); + }, source); + }; + + /** + * Executes a transducer to transform the observable sequence + * @param {Transducer} transducer A transducer to execute + * @returns {Observable} An Observable sequence containing the results from the transducer. + */ + observableProto.transduce = function(transducer) { + var source = this; + + function transformForObserver(o) { + return { + '@@transducer/init': function() { + return o; + }, + '@@transducer/step': function(obs, input) { + return obs.onNext(input); + }, + '@@transducer/result': function(obs) { + return obs.onCompleted(); + } + }; + } + + return new AnonymousObservable(function(o) { + var xform = transducer(transformForObserver(o)); + return source.subscribe( + function(v) { + try { + xform['@@transducer/step'](o, v); + } catch (e) { + o.onError(e); + } + }, + function (e) { o.onError(e); }, + function() { xform['@@transducer/result'](o); } + ); + }, source); + }; + + /* + * Performs a exclusive waiting for the first to finish before subscribing to another observable. + * Observables that come in between subscriptions will be dropped on the floor. + * @returns {Observable} A exclusive observable with only the results that happen when subscribed. + */ + observableProto.exclusive = function () { + var sources = this; + return new AnonymousObservable(function (observer) { + var hasCurrent = false, + isStopped = false, + m = new SingleAssignmentDisposable(), + g = new CompositeDisposable(); + + g.add(m); + + m.setDisposable(sources.subscribe( + function (innerSource) { + if (!hasCurrent) { + hasCurrent = true; + + isPromise(innerSource) && (innerSource = observableFromPromise(innerSource)); + + var innerSubscription = new SingleAssignmentDisposable(); + g.add(innerSubscription); + + innerSubscription.setDisposable(innerSource.subscribe( + observer.onNext.bind(observer), + observer.onError.bind(observer), + function () { + g.remove(innerSubscription); + hasCurrent = false; + if (isStopped && g.length === 1) { + observer.onCompleted(); + } + })); + } + }, + observer.onError.bind(observer), + function () { + isStopped = true; + if (!hasCurrent && g.length === 1) { + observer.onCompleted(); + } + })); + + return g; + }, this); + }; + + /* + * Performs a exclusive map waiting for the first to finish before subscribing to another observable. + * Observables that come in between subscriptions will be dropped on the floor. + * @param {Function} selector Selector to invoke for every item in the current subscription. + * @param {Any} [thisArg] An optional context to invoke with the selector parameter. + * @returns {Observable} An exclusive observable with only the results that happen when subscribed. + */ + observableProto.exclusiveMap = function (selector, thisArg) { + var sources = this, + selectorFunc = bindCallback(selector, thisArg, 3); + return new AnonymousObservable(function (observer) { + var index = 0, + hasCurrent = false, + isStopped = true, + m = new SingleAssignmentDisposable(), + g = new CompositeDisposable(); + + g.add(m); + + m.setDisposable(sources.subscribe( + function (innerSource) { + + if (!hasCurrent) { + hasCurrent = true; + + innerSubscription = new SingleAssignmentDisposable(); + g.add(innerSubscription); + + isPromise(innerSource) && (innerSource = observableFromPromise(innerSource)); + + innerSubscription.setDisposable(innerSource.subscribe( + function (x) { + var result; + try { + result = selectorFunc(x, index++, innerSource); + } catch (e) { + observer.onError(e); + return; + } + + observer.onNext(result); + }, + function (e) { observer.onError(e); }, + function () { + g.remove(innerSubscription); + hasCurrent = false; + + if (isStopped && g.length === 1) { + observer.onCompleted(); + } + })); + } + }, + function (e) { observer.onError(e); }, + function () { + isStopped = true; + if (g.length === 1 && !hasCurrent) { + observer.onCompleted(); + } + })); + return g; + }, this); + }; + + /** Provides a set of extension methods for virtual time scheduling. */ + Rx.VirtualTimeScheduler = (function (__super__) { + + function localNow() { + return this.toDateTimeOffset(this.clock); + } + + function scheduleNow(state, action) { + return this.scheduleAbsoluteWithState(state, this.clock, action); + } + + function scheduleRelative(state, dueTime, action) { + return this.scheduleRelativeWithState(state, this.toRelative(dueTime), action); + } + + function scheduleAbsolute(state, dueTime, action) { + return this.scheduleRelativeWithState(state, this.toRelative(dueTime - this.now()), action); + } + + function invokeAction(scheduler, action) { + action(); + return disposableEmpty; + } + + inherits(VirtualTimeScheduler, __super__); + + /** + * Creates a new virtual time scheduler with the specified initial clock value and absolute time comparer. + * + * @constructor + * @param {Number} initialClock Initial value for the clock. + * @param {Function} comparer Comparer to determine causality of events based on absolute time. + */ + function VirtualTimeScheduler(initialClock, comparer) { + this.clock = initialClock; + this.comparer = comparer; + this.isEnabled = false; + this.queue = new PriorityQueue(1024); + __super__.call(this, localNow, scheduleNow, scheduleRelative, scheduleAbsolute); + } + + var VirtualTimeSchedulerPrototype = VirtualTimeScheduler.prototype; + + /** + * Adds a relative time value to an absolute time value. + * @param {Number} absolute Absolute virtual time value. + * @param {Number} relative Relative virtual time value to add. + * @return {Number} Resulting absolute virtual time sum value. + */ + VirtualTimeSchedulerPrototype.add = notImplemented; + + /** + * Converts an absolute time to a number + * @param {Any} The absolute time. + * @returns {Number} The absolute time in ms + */ + VirtualTimeSchedulerPrototype.toDateTimeOffset = notImplemented; + + /** + * Converts the TimeSpan value to a relative virtual time value. + * @param {Number} timeSpan TimeSpan value to convert. + * @return {Number} Corresponding relative virtual time value. + */ + VirtualTimeSchedulerPrototype.toRelative = notImplemented; + + /** + * Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be emulated using recursive scheduling. + * @param {Mixed} state Initial state passed to the action upon the first iteration. + * @param {Number} period Period for running the work periodically. + * @param {Function} action Action to be executed, potentially updating the state. + * @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort). + */ + VirtualTimeSchedulerPrototype.schedulePeriodicWithState = function (state, period, action) { + var s = new SchedulePeriodicRecursive(this, state, period, action); + return s.start(); + }; + + /** + * Schedules an action to be executed after dueTime. + * @param {Mixed} state State passed to the action to be executed. + * @param {Number} dueTime Relative time after which to execute the action. + * @param {Function} action Action to be executed. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + VirtualTimeSchedulerPrototype.scheduleRelativeWithState = function (state, dueTime, action) { + var runAt = this.add(this.clock, dueTime); + return this.scheduleAbsoluteWithState(state, runAt, action); + }; + + /** + * Schedules an action to be executed at dueTime. + * @param {Number} dueTime Relative time after which to execute the action. + * @param {Function} action Action to be executed. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + VirtualTimeSchedulerPrototype.scheduleRelative = function (dueTime, action) { + return this.scheduleRelativeWithState(action, dueTime, invokeAction); + }; + + /** + * Starts the virtual time scheduler. + */ + VirtualTimeSchedulerPrototype.start = function () { + if (!this.isEnabled) { + this.isEnabled = true; + do { + var next = this.getNext(); + if (next !== null) { + this.comparer(next.dueTime, this.clock) > 0 && (this.clock = next.dueTime); + next.invoke(); + } else { + this.isEnabled = false; + } + } while (this.isEnabled); + } + }; + + /** + * Stops the virtual time scheduler. + */ + VirtualTimeSchedulerPrototype.stop = function () { + this.isEnabled = false; + }; + + /** + * Advances the scheduler's clock to the specified time, running all work till that point. + * @param {Number} time Absolute time to advance the scheduler's clock to. + */ + VirtualTimeSchedulerPrototype.advanceTo = function (time) { + var dueToClock = this.comparer(this.clock, time); + if (this.comparer(this.clock, time) > 0) { throw new ArgumentOutOfRangeError(); } + if (dueToClock === 0) { return; } + if (!this.isEnabled) { + this.isEnabled = true; + do { + var next = this.getNext(); + if (next !== null && this.comparer(next.dueTime, time) <= 0) { + this.comparer(next.dueTime, this.clock) > 0 && (this.clock = next.dueTime); + next.invoke(); + } else { + this.isEnabled = false; + } + } while (this.isEnabled); + this.clock = time; + } + }; + + /** + * Advances the scheduler's clock by the specified relative time, running all work scheduled for that timespan. + * @param {Number} time Relative time to advance the scheduler's clock by. + */ + VirtualTimeSchedulerPrototype.advanceBy = function (time) { + var dt = this.add(this.clock, time), + dueToClock = this.comparer(this.clock, dt); + if (dueToClock > 0) { throw new ArgumentOutOfRangeError(); } + if (dueToClock === 0) { return; } + + this.advanceTo(dt); + }; + + /** + * Advances the scheduler's clock by the specified relative time. + * @param {Number} time Relative time to advance the scheduler's clock by. + */ + VirtualTimeSchedulerPrototype.sleep = function (time) { + var dt = this.add(this.clock, time); + if (this.comparer(this.clock, dt) >= 0) { throw new ArgumentOutOfRangeError(); } + + this.clock = dt; + }; + + /** + * Gets the next scheduled item to be executed. + * @returns {ScheduledItem} The next scheduled item. + */ + VirtualTimeSchedulerPrototype.getNext = function () { + while (this.queue.length > 0) { + var next = this.queue.peek(); + if (next.isCancelled()) { + this.queue.dequeue(); + } else { + return next; + } + } + return null; + }; + + /** + * Schedules an action to be executed at dueTime. + * @param {Scheduler} scheduler Scheduler to execute the action on. + * @param {Number} dueTime Absolute time at which to execute the action. + * @param {Function} action Action to be executed. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + VirtualTimeSchedulerPrototype.scheduleAbsolute = function (dueTime, action) { + return this.scheduleAbsoluteWithState(action, dueTime, invokeAction); + }; + + /** + * Schedules an action to be executed at dueTime. + * @param {Mixed} state State passed to the action to be executed. + * @param {Number} dueTime Absolute time at which to execute the action. + * @param {Function} action Action to be executed. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + VirtualTimeSchedulerPrototype.scheduleAbsoluteWithState = function (state, dueTime, action) { + var self = this; + + function run(scheduler, state1) { + self.queue.remove(si); + return action(scheduler, state1); + } + + var si = new ScheduledItem(this, state, run, dueTime, this.comparer); + this.queue.enqueue(si); + + return si.disposable; + }; + + return VirtualTimeScheduler; + }(Scheduler)); + + /** Provides a virtual time scheduler that uses Date for absolute time and number for relative time. */ + Rx.HistoricalScheduler = (function (__super__) { + inherits(HistoricalScheduler, __super__); + + /** + * Creates a new historical scheduler with the specified initial clock value. + * @constructor + * @param {Number} initialClock Initial value for the clock. + * @param {Function} comparer Comparer to determine causality of events based on absolute time. + */ + function HistoricalScheduler(initialClock, comparer) { + var clock = initialClock == null ? 0 : initialClock; + var cmp = comparer || defaultSubComparer; + __super__.call(this, clock, cmp); + } + + var HistoricalSchedulerProto = HistoricalScheduler.prototype; + + /** + * Adds a relative time value to an absolute time value. + * @param {Number} absolute Absolute virtual time value. + * @param {Number} relative Relative virtual time value to add. + * @return {Number} Resulting absolute virtual time sum value. + */ + HistoricalSchedulerProto.add = function (absolute, relative) { + return absolute + relative; + }; + + HistoricalSchedulerProto.toDateTimeOffset = function (absolute) { + return new Date(absolute).getTime(); + }; + + /** + * Converts the TimeSpan value to a relative virtual time value. + * @memberOf HistoricalScheduler + * @param {Number} timeSpan TimeSpan value to convert. + * @return {Number} Corresponding relative virtual time value. + */ + HistoricalSchedulerProto.toRelative = function (timeSpan) { + return timeSpan; + }; + + return HistoricalScheduler; + }(Rx.VirtualTimeScheduler)); + + var AnonymousObservable = Rx.AnonymousObservable = (function (__super__) { + inherits(AnonymousObservable, __super__); + + // Fix subscriber to check for undefined or function returned to decorate as Disposable + function fixSubscriber(subscriber) { + return subscriber && isFunction(subscriber.dispose) ? subscriber : + isFunction(subscriber) ? disposableCreate(subscriber) : disposableEmpty; + } + + function setDisposable(s, state) { + var ado = state[0], subscribe = state[1]; + var sub = tryCatch(subscribe)(ado); + + if (sub === errorObj) { + if(!ado.fail(errorObj.e)) { return thrower(errorObj.e); } + } + ado.setDisposable(fixSubscriber(sub)); + } + + function AnonymousObservable(subscribe, parent) { + this.source = parent; + + function s(observer) { + var ado = new AutoDetachObserver(observer), state = [ado, subscribe]; + + if (currentThreadScheduler.scheduleRequired()) { + currentThreadScheduler.scheduleWithState(state, setDisposable); + } else { + setDisposable(null, state); + } + return ado; + } + + __super__.call(this, s); + } + + return AnonymousObservable; + + }(Observable)); + + var AutoDetachObserver = (function (__super__) { + inherits(AutoDetachObserver, __super__); + + function AutoDetachObserver(observer) { + __super__.call(this); + this.observer = observer; + this.m = new SingleAssignmentDisposable(); + } + + var AutoDetachObserverPrototype = AutoDetachObserver.prototype; + + AutoDetachObserverPrototype.next = function (value) { + var result = tryCatch(this.observer.onNext).call(this.observer, value); + if (result === errorObj) { + this.dispose(); + thrower(result.e); + } + }; + + AutoDetachObserverPrototype.error = function (err) { + var result = tryCatch(this.observer.onError).call(this.observer, err); + this.dispose(); + result === errorObj && thrower(result.e); + }; + + AutoDetachObserverPrototype.completed = function () { + var result = tryCatch(this.observer.onCompleted).call(this.observer); + this.dispose(); + result === errorObj && thrower(result.e); + }; + + AutoDetachObserverPrototype.setDisposable = function (value) { this.m.setDisposable(value); }; + AutoDetachObserverPrototype.getDisposable = function () { return this.m.getDisposable(); }; + + AutoDetachObserverPrototype.dispose = function () { + __super__.prototype.dispose.call(this); + this.m.dispose(); + }; + + return AutoDetachObserver; + }(AbstractObserver)); + + var GroupedObservable = (function (__super__) { + inherits(GroupedObservable, __super__); + + function subscribe(observer) { + return this.underlyingObservable.subscribe(observer); + } + + function GroupedObservable(key, underlyingObservable, mergedDisposable) { + __super__.call(this, subscribe); + this.key = key; + this.underlyingObservable = !mergedDisposable ? + underlyingObservable : + new AnonymousObservable(function (observer) { + return new CompositeDisposable(mergedDisposable.getDisposable(), underlyingObservable.subscribe(observer)); + }); + } + + return GroupedObservable; + }(Observable)); + + /** + * Represents an object that is both an observable sequence as well as an observer. + * Each notification is broadcasted to all subscribed observers. + */ + var Subject = Rx.Subject = (function (__super__) { + function subscribe(observer) { + checkDisposed(this); + if (!this.isStopped) { + this.observers.push(observer); + return new InnerSubscription(this, observer); + } + if (this.hasError) { + observer.onError(this.error); + return disposableEmpty; + } + observer.onCompleted(); + return disposableEmpty; + } + + inherits(Subject, __super__); + + /** + * Creates a subject. + */ + function Subject() { + __super__.call(this, subscribe); + this.isDisposed = false, + this.isStopped = false, + this.observers = []; + this.hasError = false; + } + + addProperties(Subject.prototype, Observer.prototype, { + /** + * Indicates whether the subject has observers subscribed to it. + * @returns {Boolean} Indicates whether the subject has observers subscribed to it. + */ + hasObservers: function () { return this.observers.length > 0; }, + /** + * Notifies all subscribed observers about the end of the sequence. + */ + onCompleted: function () { + checkDisposed(this); + if (!this.isStopped) { + this.isStopped = true; + for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) { + os[i].onCompleted(); + } + + this.observers.length = 0; + } + }, + /** + * Notifies all subscribed observers about the exception. + * @param {Mixed} error The exception to send to all observers. + */ + onError: function (error) { + checkDisposed(this); + if (!this.isStopped) { + this.isStopped = true; + this.error = error; + this.hasError = true; + for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) { + os[i].onError(error); + } + + this.observers.length = 0; + } + }, + /** + * Notifies all subscribed observers about the arrival of the specified element in the sequence. + * @param {Mixed} value The value to send to all observers. + */ + onNext: function (value) { + checkDisposed(this); + if (!this.isStopped) { + for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) { + os[i].onNext(value); + } + } + }, + /** + * Unsubscribe all observers and release resources. + */ + dispose: function () { + this.isDisposed = true; + this.observers = null; + } + }); + + /** + * Creates a subject from the specified observer and observable. + * @param {Observer} observer The observer used to send messages to the subject. + * @param {Observable} observable The observable used to subscribe to messages sent from the subject. + * @returns {Subject} Subject implemented using the given observer and observable. + */ + Subject.create = function (observer, observable) { + return new AnonymousSubject(observer, observable); + }; + + return Subject; + }(Observable)); + + /** + * Represents the result of an asynchronous operation. + * The last value before the OnCompleted notification, or the error received through OnError, is sent to all subscribed observers. + */ + var AsyncSubject = Rx.AsyncSubject = (function (__super__) { + + function subscribe(observer) { + checkDisposed(this); + + if (!this.isStopped) { + this.observers.push(observer); + return new InnerSubscription(this, observer); + } + + if (this.hasError) { + observer.onError(this.error); + } else if (this.hasValue) { + observer.onNext(this.value); + observer.onCompleted(); + } else { + observer.onCompleted(); + } + + return disposableEmpty; + } + + inherits(AsyncSubject, __super__); + + /** + * Creates a subject that can only receive one value and that value is cached for all future observations. + * @constructor + */ + function AsyncSubject() { + __super__.call(this, subscribe); + + this.isDisposed = false; + this.isStopped = false; + this.hasValue = false; + this.observers = []; + this.hasError = false; + } + + addProperties(AsyncSubject.prototype, Observer, { + /** + * Indicates whether the subject has observers subscribed to it. + * @returns {Boolean} Indicates whether the subject has observers subscribed to it. + */ + hasObservers: function () { + checkDisposed(this); + return this.observers.length > 0; + }, + /** + * Notifies all subscribed observers about the end of the sequence, also causing the last received value to be sent out (if any). + */ + onCompleted: function () { + var i, len; + checkDisposed(this); + if (!this.isStopped) { + this.isStopped = true; + var os = cloneArray(this.observers), len = os.length; + + if (this.hasValue) { + for (i = 0; i < len; i++) { + var o = os[i]; + o.onNext(this.value); + o.onCompleted(); + } + } else { + for (i = 0; i < len; i++) { + os[i].onCompleted(); + } + } + + this.observers.length = 0; + } + }, + /** + * Notifies all subscribed observers about the error. + * @param {Mixed} error The Error to send to all observers. + */ + onError: function (error) { + checkDisposed(this); + if (!this.isStopped) { + this.isStopped = true; + this.hasError = true; + this.error = error; + + for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) { + os[i].onError(error); + } + + this.observers.length = 0; + } + }, + /** + * Sends a value to the subject. The last value received before successful termination will be sent to all subscribed and future observers. + * @param {Mixed} value The value to store in the subject. + */ + onNext: function (value) { + checkDisposed(this); + if (this.isStopped) { return; } + this.value = value; + this.hasValue = true; + }, + /** + * Unsubscribe all observers and release resources. + */ + dispose: function () { + this.isDisposed = true; + this.observers = null; + this.exception = null; + this.value = null; + } + }); + + return AsyncSubject; + }(Observable)); + + var AnonymousSubject = Rx.AnonymousSubject = (function (__super__) { + inherits(AnonymousSubject, __super__); + + function subscribe(observer) { + return this.observable.subscribe(observer); + } + + function AnonymousSubject(observer, observable) { + this.observer = observer; + this.observable = observable; + __super__.call(this, subscribe); + } + + addProperties(AnonymousSubject.prototype, Observer.prototype, { + onCompleted: function () { + this.observer.onCompleted(); + }, + onError: function (error) { + this.observer.onError(error); + }, + onNext: function (value) { + this.observer.onNext(value); + } + }); + + return AnonymousSubject; + }(Observable)); + + /** + * Used to pause and resume streams. + */ + Rx.Pauser = (function (__super__) { + inherits(Pauser, __super__); + + function Pauser() { + __super__.call(this); + } + + /** + * Pauses the underlying sequence. + */ + Pauser.prototype.pause = function () { this.onNext(false); }; + + /** + * Resumes the underlying sequence. + */ + Pauser.prototype.resume = function () { this.onNext(true); }; + + return Pauser; + }(Subject)); + + if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) { + root.Rx = Rx; + + define(function() { + return Rx; + }); + } else if (freeExports && freeModule) { + // in Node.js or RingoJS + if (moduleExports) { + (freeModule.exports = Rx).Rx = Rx; + } else { + freeExports.Rx = Rx; + } + } else { + // in a browser or Rhino + root.Rx = Rx; + } + + // All code before this point will be filtered from stack traces. + var rEndingLine = captureLine(); + +}.call(this)); diff --git a/manifest.json b/manifest.json index 1ae13b8..59a4d9e 100644 --- a/manifest.json +++ b/manifest.json @@ -24,6 +24,7 @@ "background": { "scripts": [ + "libs/rx.all.js", "background.js" ] },